Ef6 + postgresql + Quartz

171 阅读1分钟

一 实现一个计划任务代码

1 project

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
	<PackageReference Include="Quartz.Extensions.Hosting" Version="3.5.0" />
  </ItemGroup>

2 program.cs

using FlashFxPayment.Worker;
using Quartz;
//using 

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices( (hostContext,services) =>
    {
        // services.AddHostedService<Worker>();
        // Add the required Quartz.NET services

        var configuration = hostContext.Configuration;


       // services.AddDbContextPool();


        services.AddQuartz(q =>
        {
            // Use a Scoped container to create jobs. I'll touch on this later
            q.UseMicrosoftDependencyInjectionScopedJobFactory();

            // Create a "key" for the job
            var jobKey = new JobKey("HelloWorldJob");
            // Register the job with the DI container
            q.AddJob<FlashFxPayment.Worker.Properties.Job.HelloWorldJob>(opts => opts.WithIdentity(jobKey));

            // Create a trigger for the job
            q.AddTrigger(opts => opts
                .ForJob(jobKey) // link to the HelloWorldJob
                .WithIdentity("HelloWorldJob-trigger") // give the trigger a unique name
                .WithCronSchedule("0/5 * * * * ?")); // run every 5 seconds

        });

        // Add the Quartz.NET hosted service
          services.AddQuartzHostedService(
            q => q.WaitForJobsToComplete = true);

    })
    .Build();

await host.RunAsync();

3 Properties/Job/HelloWorldJob.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlashFxPayment.Worker.Properties.Job;
using Microsoft.Extensions.Logging;
using Quartz;
using System.Threading.Tasks;


public class HelloWorldJob : IJob
{
    private readonly ILogger<HelloWorldJob> _logger;
    public HelloWorldJob(ILogger<HelloWorldJob> logger)
    {
        _logger = logger;
    }

    public Task Execute(IJobExecutionContext context)
    {
        _logger.LogInformation("Hello world!");
        Console.WriteLine("hello world-"+DateTime.Now.ToString());
        return Task.CompletedTask;
    }
}