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

时间:2012-07-28 18:23:11

标签: c#

我是C#的新手,但java有在指定时间执行指定任务的方法,所以使用c#如何做

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

t.schedule(task1, 3000);

4 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:4)

使用Anonymous MethodsObject Initializer

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

答案 2 :(得分: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!");
    }
}

答案 3 :(得分: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);
        }
    }
}