如何在指定时间执行特定任务

4

我是C#的新手,但Java有一种方法可以在指定的时间执行指定的任务,那么使用C#如何实现呢?

Timer t=new Timer();
TimerTask task1 =new TimerTask()           

t.schedule(task1, 3000);

添加一个带有回调函数的计时器,并检查所需的条件并执行您想要的操作。 - Haseeb Asif
1
可能是C# 在特定时间执行函数的重复问题。 - Peter Ritchie
4个回答

7
你可以在这里获得C#计时器完整的教程:http://www.dotnetperls.com/timer 简而言之:
using System;
using System.Collections.Generic;
using System.Timers;

public static class TimerExample // In App_Code folder
{
    static Timer _timer; // From System.Timers
    static List<DateTime> _l; // Stores timer results
    public static List<DateTime> DateList // Gets the results
    {
        get
        {
            if (_l == null) // Lazily initialize the timer
            {
                Start(); // Start the timer
            }
            return _l; // Return the list of dates
        }
    }
    static void Start()
    {
        _l = new List<DateTime>(); // Allocate the list
        _timer = new Timer(3000); // Set up the timer for 3 seconds
        //
        // Type "_timer.Elapsed += " and press tab twice.
        //
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Enabled = true; // Enable it
    }
    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _l.Add(DateTime.Now); // Add date on each timer event
    }
}

欢迎来到SO,@mssb。这个回答解决了你的问题吗?如果是的话,你应该点击答案左边的“打勾”标记将其标记为已接受。 - Kjartan
C# 不提供像构造函数一样的 new Timer(3000);。 - mssb
.NET确实有那个计时器构造函数。将他的所有代码包含在你的类中。他正在使用System.Timers.Timer @mssb - nawfal

4

使用匿名方法对象初始化器

var timer = new Timer { Interval = 5000 };
timer.Tick += (sender, e) =>
    {
        MessageBox.Show(@"Hello world!");
    };

3

以下是一个样例:

public class Timer1
{

    public static void Main()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
        // Set the Interval to 5 seconds.
        aTimer.Interval=5000;
        aTimer.Enabled=true;

        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Hello World!");
    }
}

1
using System;
using System.Threading;

namespace ConsoleApplication6
{
    class Program
    {

        public void TimerTask(object state)
        {
            //Do your task
            Console.WriteLine("oops");
        }

        static void Main(string[] args)
        {
            var program = new Program();
            var timer = new Timer(program.TimerTask, 
                                  null, 
                                  3000, 
                                  Timeout.Infinite);
            Thread.Sleep(10000);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接