首页 .Net .NET Core(C#)实现定时任务的三种方法(Timer、Quartz.NET、sleep和Task)

.NET Core(C#)实现定时任务的三种方法(Timer、Quartz.NET、sleep和Task)

1、使用System.Timers.Timer和System.Threading.Timer实现定时任务

1)使用System.Timers.Timer实现

文档:.NET Core(C#) System.Timers.Timer使用实现定时任务及示例代码

2)使用System.Threading.Timer实现

文档:.NET Core(C#) System.Threading.Timer使用实现定时任务及示例代码

2、使用Quartz.NET实现定时任务

文档:.NET Core(C#) Quartz.NET实现定时任务的方法及示例代码

3、使用while和sleep及Task实现定时任务

public >TaskTimer
{
    private static int _interval = 1000;//间隔时间
    private static bool _isRuning = false;
    private static Action _action = () =>
    {
        while (_isRuning)
        {
            taskAction();
            System.Threading.Thread.Sleep(_interval);
        }
    };
    private static Action taskAction;
    Task timer = new Task(_action);
    public TaskTimer(int interval, Action action)
    {
        _interval = interval;
        taskAction = action;
    }
    public void Start()
    {
        _isRuning = true;
        if (timer == null)
            timer = new Task(_action);
        timer.Start();
    }
    public void Stop()
    {
        _isRuning = false;
        timer.Wait();
        timer.Dispose();
        timer = null;
    }
}

使用示例:

TaskTimer timer = new TaskTimer(1000, () =>
            {
                Console.WriteLine(DateTime.Now);
            });
timer.Start();//启动
timer.Stop();//停止
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。