一个时间间隔内的C#Run方法 [英] C# Run method in a time interval

查看:61
本文介绍了一个时间间隔内的C#Run方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法可以从api获取数据并将其保存到JSON文件.

I have this method that gets data from an api and saves it to a JSON file.

如何获取每小时更新一次的JSON文件.

How can I get the JSON file to be updated every hour on the hour.

 public void saveUsers()
    {
        string  uri = "https://****dd.harvestapp.com/people";

        using (WebClient webClient = new WebClient())
        {
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.Accept] = "application/json";
            webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes(usernamePassword));

            string response = webClient.DownloadString(uri);

            File.WriteAllText(jsonPath, response);
        }
    }

推荐答案

使用计时器,在 saveUsers()方法中添加对象源,ElapsedEventArgs e 参数并使其生效静态

Use timer, add object source, ElapsedEventArgs e parameters in your saveUsers() method and make it static

private static System.Timers.Timer timer;

public static void Main()
{
    timer = new System.Timers.Timer(10000);

    timer.Elapsed += new ElapsedEventHandler(saveUsers);

    timer.Interval = 3600000;
    timer.Enabled = true;

}

 public static void saveUsers(object source, ElapsedEventArgs e)
    {
        string  uri = "https://****dd.harvestapp.com/people";
        using (WebClient webClient = new WebClient())
        {
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.Accept] = "application/json";
            webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes(usernamePassword));

            string response = webClient.DownloadString(uri);


            File.WriteAllText(jsonPath, response);

        }

    }

更新

假设您有一个 MVC 控制器名称 Home ,则可以从 index 方法

Suppose you have a MVC controller name Home then you can start the timer from the index method

public class HomeController : Controller
    {
        private static System.Timers.Timer timer;
        public ActionResult Index()
        {
            timer = new System.Timers.Timer(10000);
            timer.Elapsed += new ElapsedEventHandler(saveUsers);
            timer.Interval = 3600000;
            timer.Enabled = true;

            return View();
        }
    }

请记住一件事,因为您希望每隔一个小时运行一次计时器,这样垃圾回收器可能会在方法调用之前停止计时器,您需要保持计时器处于活动状态,可以在启动计时器后以这种方式使计时器保持活动状态

And keep one thing in mind because you want to run the timer in an hour interval so may garbage collector stop the timer before method call, you need to keep alive the timer, you can keep timer alive this way after starting the timer

GC.KeepAlive(timer);

这篇关于一个时间间隔内的C#Run方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆