首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何每n分钟运行一次任务

如何每n分钟运行一次任务
EN

Stack Overflow用户
提问于 2018-08-06 05:46:14
回答 5查看 4K关注 0票数 -3

我写了一个代码来更新DDNS,它工作得很好。我现在需要每隔n分钟运行一次这段代码:我该怎么做呢?

我尝试使用:

代码语言:javascript
复制
while (true)
{
    this.DoMyMethod();
    Thread.Sleep(TimeSpan.FromMinutes(1));
}

我还是遇到了一些麻烦。每隔n分钟运行此任务的最佳方式是什么?

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;

namespace GoogleDDNS
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (username.Text == "")
            {
                System.Windows.MessageBox.Show("Please enter the username");
                username.Focus();
                return;
            }
            if (password.Text == "")
            {
                System.Windows.MessageBox.Show("Please enter the password");
                password.Focus();
                return;
            }
            if (subdomain.Text == "")
            {
                System.Windows.MessageBox.Show("Please enter the subdomain");
                subdomain.Focus();
                return;
            }

            var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
            var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);

            responseddns.Content = response;

            Properties.Settings.Default.usernamesave = username.Text;
            Properties.Settings.Default.passwordsave = password.Text;
            Properties.Settings.Default.subdomainsave = subdomain.Text;

            Properties.Settings.Default.Save();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            username.Text = Properties.Settings.Default.usernamesave;
            password.Text = Properties.Settings.Default.passwordsave;
            subdomain.Text = Properties.Settings.Default.subdomainsave;
        }
    }
}
EN

回答 5

Stack Overflow用户

发布于 2018-08-06 06:16:38

为什么不使用System.Threading.Timer来实现呢?

Microsoft documentation中,假设您有以下示例类:

代码语言:javascript
复制
class StatusChecker
{
    private int invokeCount;
    private int maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if (invokeCount == maxCount)
        {
            // Reset the counter and signal the waiting thread.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}

然后,您可以创建一个Timer来每隔n秒运行一次CheckStatus,如下所示:

代码语言:javascript
复制
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(5);

// creates a Timer to call CheckStatus() with autoEvent as argument,
// starting with 1 second delay and calling every 2 seconds.
var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 2000);
autoEvent.WaitOne();
票数 2
EN

Stack Overflow用户

发布于 2018-08-06 05:56:46

看看这个。我记得一位同事刚才用过它:

FluentScheduler - [Project Site]

用法:

代码语言:javascript
复制
// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();

会满足你的需求。

票数 0
EN

Stack Overflow用户

发布于 2018-08-06 11:35:06

我用计时器,代码是

代码语言:javascript
复制
using System;
using System.Net;
using System.Timers;

static void Main(string[] args)
        {
            Console.WriteLine("The system is start at {0}", DateTime.Now);
            Timer t = new Timer(10000);
            t.Enabled = true;
            t.Elapsed += T_Elapsed;
            Console.ReadKey();

        }
        private static void T_Elapsed(object sender, ElapsedEventArgs e)
        {
            //write your code
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51698490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档