code-porter-233

导航

.NET Core项目使用Quartz实现简单的调度任务

创建一个.NET Core 3.1控制台应用程序。

引入项目所需的依赖:

dotnet add package Unity
dotnet add package Quartz
dotnet add package Microsoft.EntityFrameworkCore 3.1.0
dotnet add package Microsoft.EntityFrameworkCore.SqlServer 3.1.0

新建一张表用来存放任务配置:

-- ----------------------------
-- Table structure for bjScheduleConfigModel
-- ----------------------------
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[ScheduleConfigModel]') AND type IN ('U'))
    DROP TABLE [dbo].[bjScheduleConfigModel]
GO

CREATE TABLE [dbo].[ScheduleConfigModel] (
  [ScheduleConfigId] int  IDENTITY(1,1) NOT NULL,
  [JobName] varchar(50) COLLATE Chinese_PRC_CI_AS  NOT NULL,
  [CronExpression] varchar(20) COLLATE Chinese_PRC_CI_AS  NOT NULL,
  [Enable] int  NOT NULL,
  [LastExecuteTime] datetime  NULL,
  [CreateDate] datetime  NOT NULL,
  [CreateBy] varchar(50) COLLATE Chinese_PRC_CI_AS  NOT NULL,
  [UpdateDate] datetime  NOT NULL,
  [UpdateBy] varchar(50) COLLATE Chinese_PRC_CI_AS  NOT NULL
)
GO

ALTER TABLE [dbo].[bjScheduleConfigModel] SET (LOCK_ESCALATION = TABLE)
GO


-- ----------------------------
-- Primary Key structure for table bjScheduleConfigModel
-- ----------------------------
ALTER TABLE [dbo].[ScheduleConfigModel] ADD CONSTRAINT [PK_ScheduleConfigModel] PRIMARY KEY CLUSTERED ([ScheduleConfigId])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)  
ON [PRIMARY]
GO

新建DbContext类:

public class ScheduleDbContext : DbContext
{
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
     base.OnConfiguring(optionsBuilder);
      optionsBuilder.UseSqlServer("Server={{IP}};Database={{databaseName}};User ID={{username}};Password={{password}};");
   }
   
  public DbSet<ScheduleConfigModel> ScheduleConfigDbSet { get; set; }
}

新建ScheduleContainer类(依赖注入):

public class ScheduleContainer
{
    private ScheduleContainer()
    {

    }

    private static IUnityContainer UnityContainer { get; set; }

    public static IUnityContainer CreateInstance()
    {
        if (UnityContainer == null)
        {
            UnityContainer = new UnityContainer();
            UnityContainer.RegisterType<ScheduleDbContext>();

            var stdSchedulerFactory = new StdSchedulerFactory();
            UnityContainer.RegisterInstance<ISchedulerFactory>(stdSchedulerFactory);
        }

        return UnityContainer;
    }
}

新建一个Job任务类:

public class TestJob : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        return Task.Factory.StartNew(() =>
        {
            string executeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine($"Job:TestJob, execute time: {executeTime}");
        });
    }
}

下面开始编写任务调度代码:

public class Schedule
{
    public static async void Start()
    {
        IUnityContainer container = ScheduleContainer.CreateInstance();
        ISchedulerFactory schedulerFactory = container.Resolve<ISchedulerFactory>();
        IScheduler scheduler = await schedulerFactory.GetScheduler();
        await scheduler.Start();

        Console.WriteLine("任务调度器已启动");

        ScheduleDbContext context = container.Resolve<ScheduleDbContext>();
        List<ScheduleConfigModel> configs = context.ScheduleConfigDbSet.Where(e => e.Enable == 1).ToList();

        foreach (var config in configs)
        {
            var type = Type.GetType(string.Format("JobService.Jobs.{0}", config.JobName));
            var job = JobBuilder.Create(type).Build();
            var tigger = TriggerBuilder.Create().WithCronSchedule(config.CronExpression).Build();

            await scheduler.ScheduleJob(job, tigger);

            Console.WriteLine($"Job:{config.JobName}添加任务调度成功");
        }

        while (!scheduler.IsShutdown)
        { 
            //防止程序退出
        }
    }
}

效果:

 

posted on 2022-09-22 15:45  瞬间空白  阅读(254)  评论(0编辑  收藏  举报