惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
D
DataBreaches.Net
宝玉的分享
宝玉的分享
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
人人都是产品经理
人人都是产品经理
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
腾讯CDC
博客园_首页
The Cloudflare Blog
S
SegmentFault 最新的问题
C
Check Point Blog
美团技术团队
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale

博客园 - 我有我奥妙

【BenchmarkDotNet】测试多方式的对象映射 【自动注入】.NET8/.NETCore 依赖注入:自动注入项目中所有接口和自定义类 【排名】处理同分数的排名 【模型验证】未被异常捕获到 【Ant Design Vue】相关 【根节点】C#找树形数据的根节点Id 【C#】枚举值 【ECharts】图表自定义显示标题 【消息队列】介绍 【Nginx】Windows部署Vue 设计模式(一)-介绍 【.NetCore】创建本机的静态文件服务器 NLog(一)-使用示例 【nssm】windows上netcore注册为服务 【字符串排序】C#和前端js排序问题 【长路经】C#读取文件抛出FileNotFoundException异常 【RestSharp】常用的几个请求方式 【笔记软件】Obsidian的使用 【浏览器扩展】编写Firefox和Chrome的扩展程序
【Quartz】.Net8使用定时任务
我有我奥妙 · 2025-04-20 · via 博客园 - 我有我奥妙

添加引用

	<ItemGroup>
		<PackageReference Include="Quartz.AspNetCore" Version="3.14.0" />
		<PackageReference Include="NLog" Version="5.4.0" />
		<PackageReference Include="NLog.Web.AspNetCore" Version="5.4.0" />
	</ItemGroup>

Program.cs文件

using Quartz.AspNetCore;
using Quartz;
using NLog.Web;

namespace Fox.Tasks
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddQuartz(q =>
            {
                q.ExecuteByCron<SendEmailJob>("0 0/2 * * * ?");
                q.ExecuteByCron<SendTipsJob>("0 0/3 * * * ?");
            });

            builder.Services.AddQuartzServer(options =>
            {
                options.WaitForJobsToComplete = true;
            });

            builder.Host.UseNLog();

            var app = builder.Build();

            app.MapGet("/", () => "Hello World!");

            app.Run();
        }
    }
}

QuartzExtensions扩展类

using Quartz;

namespace Fox.Tasks
{
    public static class QuartzExtensions
    {
        public static IServiceCollectionQuartzConfigurator ExecuteByCron<T>(
            this IServiceCollectionQuartzConfigurator configurator,
            string cronExpression) where T : IJob
        {
            var jobName = typeof(T).Name;
            var jobKey = new JobKey(jobName);

            configurator.AddJob<T>(opts => opts.WithIdentity(jobKey));

            configurator.AddTrigger(opts => opts
                .ForJob(jobKey)
                .WithIdentity($"{jobName}-trigger")
                .WithCronSchedule(cronExpression));

            return configurator;
        }
    }
}

任务SendEmailJob

using Quartz;

namespace Fox.Tasks
{
    public class SendEmailJob : IJob
    {
        private readonly ILogger<SendEmailJob> _logger;

        public SendEmailJob(ILogger<SendEmailJob> logger)
        {
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Delay(10);

            _logger.LogError(" => 已运行1 ");
        }
    }
}

任务SendTipsJob

using Quartz;

namespace Fox.Tasks
{
    public class SendTipsJob: IJob
    {
        private readonly ILogger<SendTipsJob> _logger;

        public SendTipsJob(ILogger<SendTipsJob> logger)
        {
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Delay(10);

            _logger.LogError(" => 已运行2 ");
        }
    }
}

nlog.config配置

<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<targets async="true">
		<target name="file" xsi:type="File" FileName="logs/${shortdate}_${level}.txt" layout="[${longdate}] ${logger} ${message} ${newline}" />
	</targets>
	<rules>
		<logger name="*" Level="Fatal" writeTo="file" />
		<logger name="*" Level="Error" writeTo="file" />
		<logger name="*" Level="Warn" writeTo="file" />
		<logger name="*" Level="Info" writeTo="file" />
		<logger name="*" Level="Debug" writeTo="file" />
		<logger name="*" Level="Trace" writeTo="file" />
	</rules>
</nlog>