.net core 任务调度

.net core 任务调度

有时候需要在后台定时执行一些任务,这里有两种示例:

1、BackgroundService

using Microsoft.Extensions.Hosting;using System;using System.Threading;using System.Threading.Tasks;namespace Vote.Tools{    public class AccessTokenJob : BackgroundService    {
     //重写
ExecuteAsync
    protected override async Task ExecuteAsync(CancellationToken stoppingToken) { 
      
try { while (!stoppingToken.IsCancellationRequested) {
            
do {
                //需要执行的任务
                .......
} while (string.IsNullOrEmpty(token));//token获取失败继续执行 await Task.Delay(7200000, stoppingToken); //7200秒执行一次 } } catch (Exception ex) { throw new Exception(); } } }}

并且在Startup.cs ConfigureServices方法下配置

services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, AccessTokenJob>();//第二个为工作调度的类名

2、使用Pomelo.AspNetCore.TimedJob

Nuget添加Pomelo.AspNetCore.TimedJob

Startup.cs ConfigureServices方法下配置

services.AddTimedJob();

using BLL.Manager;using BLL.Vote;using Models.Manager.Plan;using Pomelo.AspNetCore.TimedJob;using System.Collections.Generic;using System.Linq;namespace Vote.Tools{    public class EmpRecordJob: Pomelo.AspNetCore.TimedJob.Job    {        // Begin 起始时间;Interval执行时间间隔,单位是毫秒        //SkipWhileExecuting是否等待上一个执行完成,true为等待;        [Invoke(Begin = "2019-06-20 9:00", Interval = 1000 * 3600 , SkipWhileExecuting = true)]        public void Run()        {            //需要执行的代码        }    }}

推荐阅读