4

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

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

t.schedule(task1, 3000);
4

4 回答 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
    }
}
于 2012-07-28T18:26:17.330 回答
4

使用Anonymous MethodsObject Initializer

var timer = new Timer { Interval = 5000 };
timer.Tick += (sender, e) =>
    {
        MessageBox.Show(@"Hello world!");
    };
于 2012-07-28T20:01:13.937 回答
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!");
    }
}
于 2012-07-28T18:32:12.460 回答
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);
        }
    }
}
于 2012-07-28T18:26:40.257 回答