如何每n分钟执行一次任务

时间:2018-08-05 21:46:14

标签: c#

我编写了更新DDNS的代码,效果很好。我现在需要每n分钟运行一次此代码:我该怎么做?

我尝试使用:

while (true)
{
    this.DoMyMethod();
    Thread.Sleep(TimeSpan.FromMinutes(1));
}

我仍然遇到一些麻烦。每n分钟运行一次此任务的最佳方法是什么?

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;
        }
    }
}

5 个答案:

答案 0 :(得分:2)

为什么不使用System.Threading.Timer

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

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来每CheckStatus秒运行一次n,例如:

// 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();

答案 1 :(得分:0)

我使用计时器, 代码是

table_b

答案 2 :(得分:0)

这是为我解决的问题。

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);
            //MessageBox.Show(response);
            responseddns.Content = response;



            Properties.Settings.Default.usernamesave = username.Text;
            Properties.Settings.Default.passwordsave = password.Text;
            Properties.Settings.Default.subdomainsave = subdomain.Text;
            //Properties.Settings.Default.intervalsave = interval.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;
            //interval.Text = Properties.Settings.Default.intervalsave;


            System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
            MyTimer.Interval = (1 * 60 * 1000); // 45 mins
            MyTimer.Tick += new EventHandler(MyTimer_Tick);
            MyTimer.Start();

        }
        private void MyTimer_Tick(object sender, EventArgs e)
        {
            var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
            var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
            //MessageBox.Show(response);
            responseddns.Content = response;
            //this.Close();
        }

    }
}

答案 3 :(得分:0)

某处遇到此代码

class Program
{
    static void Main(string[] args)
    {
        int Interval = 5;

        CancellationTokenSource cancellation = new CancellationTokenSource();
        Console.WriteLine("Start Loop...");
        RepeatActionEvery(() => Console.WriteLine("Hi time {0}",DateTime.Now), TimeSpan.FromMinutes(Interval), cancellation.Token).Wait();
        Console.WriteLine("Finish loop!!!");


    }

    public static async Task RepeatActionEvery(Action action, TimeSpan interval, CancellationToken cancellationToken)
    {
        while (true)
        {
            action();
            Task task = Task.Delay(interval, cancellationToken);

            try
            {
                await task;
            }

            catch (TaskCanceledException)
            {
                return;
            }
        }
    }
}

答案 4 :(得分:-1)

看看这个。我回想起一个同事使用它的一段时间:

FluentScheduler-[Project Site]

用法:

// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();

将满足您的需求。