.net core 使用定时任务 quartz.net 实例

项目是core3.1的

 

只用引用一个包就可以了

引用配置Quartz

首先创建一个任务工厂

public class CronJobFactory : IJobFactory
{
    private readonly IServiceProvider _serviceProvider;

    public CronJobFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
    }
    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        return _serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob;
    }

    public void ReturnJob(IJob job)
    {
    }
}

 

创建一个HelloJob类并实现  IJob接口      自定义任务

public class HelloJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        await Console.Out.WriteLineAsync($"{DateTime.Now:HH:mm:ss}--Hello World!");
    }
}

新建SchedulerCenter类      调度中心

public class SchedulerCenter
{
    private readonly IJobFactory _jobFactory;
    private readonly ISchedulerFactory _schedulerFactory;
    private IScheduler _scheduler;
    public SchedulerCenter(IJobFactory jobFactory, ISchedulerFactory schedulerFactory)
    {
        _jobFactory = jobFactory;
        _schedulerFactory = schedulerFactory;
    }
    public async void StartScheduler()
    {
        //1、从工厂获取调度程序实例
        _scheduler = await _schedulerFactory.GetScheduler();

        // 替换默认工厂
        _scheduler.JobFactory = this._jobFactory;

        //2、打开调度器
        await _scheduler.Start();

        //3、定义作业详细信息并将其与HelloJob任务相关联
        IJobDetail job = JobBuilder.Create<HelloJob>()
            .WithIdentity("HelloJob", "HelloJobGroup")
            .Build();

        //4、配置触发条件:立即触发作业运行,然后每10秒重复一次
        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("HelloJob", "HelloJobGroup")
            .StartNow()
            .WithSimpleSchedule(x => x
                .WithIntervalInSeconds(10)
                .RepeatForever())
            .Build();

        //5、将作业与触发条件添加到调度实例并进行关联
        await _scheduler.ScheduleJob(job, trigger);
    }
    public void StopScheduler()
    {
        _scheduler?.Shutdown(true).Wait(30000);
        _scheduler = null;
    }
}

 

 

接下来在startup.cs中的ConfigureServices增加一些配置注入

//注入调度中心
services.AddSingleton<SchedulerCenter>();

//注入Quartz任何工厂及调度工厂
services.AddSingleton<IJobFactory, CronJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();

//注入HelloJob
services.AddTransient<HelloJob>();

 在Startup类的Configure方法中进行启动配置

//获取调度中心实例
var quartz = app.ApplicationServices.GetRequiredService<SchedulerCenter>();

lifetime.ApplicationStarted.Register(() =>
{
    quartz.StartScheduler(); //项目启动后启动调度中心
});

lifetime.ApplicationStopped.Register(() =>
{
    quartz.StopScheduler();  //项目停止后关闭调度中心
});

 在helloJob中实现具体的调用

public class HelloJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        
        await Console.Out.WriteLineAsync($"{DateTime.Now:HH:mm:ss}");
    }
}

注意!!!!!!!项目启动后,记得重新在地址栏重新回车一下,不然不会自动执行!!!!!!

 

 

 

 

参考引用:.Net Core(五) 引入定时任务Quartz.Net - 咸鱼翻身? - 博客园

posted @ 2024-11-05 09:25  路边有一棵草  阅读(106)  评论(0编辑  收藏  举报