当前位置: 首页 > news >正文

使用Linux Systemd部署DotNet Quartz.Net定时任务

开发环境

  • Windows 10 WSL2
  • Ubuntu 22.04
  • DotNet 6
  • Quartz.Net

代码实战

  1. 新建dotnet项目,添加引用Quartz.net包
    入口程序:
static void Main(string[] args){IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).Build();//Serilogvar logPath = configuration["Serilog:Path"]?.ToString();var logTemplate = configuration["Serilog:Template"]?.ToString();Log.Logger = new LoggerConfiguration().MinimumLevel.Information().WriteTo.Console().WriteTo.File(logPath,rollingInterval: RollingInterval.Day,outputTemplate: logTemplate,rollOnFileSizeLimit: true,fileSizeLimitBytes: 52428800 // 50MB).CreateLogger();CreateHostBuilder(args, configuration).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args, IConfiguration configuration){IHostBuilder hostBuilder = Host.CreateDefaultBuilder(args).UseSerilog();hostBuilder.ConfigureServices((hostContext, services) =>{services.AddQuartz(q =>{q.UseMicrosoftDependencyInjectionJobFactory();q.AddJobAndTrigger<TestJob>(configuration);q.AddJobAndTrigger<Test2Job>(configuration);});services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);});//Windows//if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))//{ hostBuilder.UseWindowsService(); }//Linuxif (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){ hostBuilder.UseSystemd(); }return hostBuilder;}

QuartzConfigurator:

    public static class QuartzConfigurator{public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config) where T : IJob{// Use the name of the IJob as the appsettings.json keystring jobName = typeof(T).Name;// Try and load the schedule from configurationvar configKey = $"Quartz:{jobName}";var cronSchedule = config[configKey];// Some minor validationif (string.IsNullOrEmpty(cronSchedule)){throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");}// register the job as beforevar jobKey = new JobKey(jobName);quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));quartz.AddTrigger(opts => opts.ForJob(jobKey).WithIdentity(jobName + "_trigger").WithCronSchedule(cronSchedule)); // use the schedule from configuration}}

appsettings.json:

{"Serilog": {"Path": "Logs/job.log","Template": "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff} LogLevel:{Level} Message:{Message} {Exception}"},"Quartz": {"Test2Job": "0/8 * * * * ?","TestJob": "0/5 * * * * ?"}
}
  1. 新建.service文件,用作linux服务配置
[Unit]
Description=BPM.JobMgr service[Service]
# The systemd service file must be configured with Type=notify to enable notifications.
Type=notify
# systemd will run this executable to start the service
WorkingDirectory=/srv/bpmjobmgr
ExecStart=/usr/bin/dotnet /srv/bpmjobmgr/BPM.JobMgr.dll
# to query logs using journalctl, set a logical name here  
SyslogIdentifier=bpmjobmgr# Use your username to keep things simple.
# If you pick a different user, make sure dotnet and all permissions are set correctly to run the app
# To update permissions, use 'chown yourusername -R /srv/Worker' to take ownership of the folder and files,
#       Use 'chmod +x /srv/Worker/MyService' to allow execution of the executable file
User=root# This gives time to MyService to shutdown gracefully.
TimeoutStopSec=300[Install]
WantedBy=multi-user.target
  1. windows10安装WSL2,建议选用Ubuntu 22.04版本方便启用systemd。WSL2安装dotnet6 runtime。
    https://learn.microsoft.com/zh-cn/windows/wsl/systemd

    https://learn.microsoft.com/zh-cn/dotnet/core/install/linux-ubuntu-install?tabs=dotnet8&pivots=os-linux-ubuntu-2204#ubuntu-2204

  2. Linux Systemd配置

.service文件cp到Ubuntu的/etc/systemd/system/ 目录下

cp /mnt/c/benj/bpmjobmgr.service /etc/systemd/system/

reload配置文件

systemctl daemon-reload

检查配置文件

systemctl status bpmjobmgr

enable并启动服务

systemctl enable bpmjobmgr
systemctl start bpmjobmgr
  1. 执行效果
    在这里插入图片描述

http://www.mrgr.cn/news/2666.html

相关文章:

  • clickhouse_driver
  • RUST知识框架与学习框架
  • fastadmin 控制器的权限管理
  • asyncua模块实现OPC UA通讯
  • 什么是多组学整合
  • 【C# 】使用List<实体类>
  • 逻辑与集合论基础及其在编程中的应用
  • 揭秘GPT-5,探索未来人工智能的无限可能
  • 深入理解指针(五)
  • 花钱买不到系列—linux虚拟地址空间
  • 【技术方案】智慧城市大数据平台技术方案(Doc原件)
  • 来聊一聊JVM
  • MySQL:从入门到放弃
  • 一起学习LeetCode热题100道(50/100)
  • CSS有趣知识
  • JS面试题3
  • Redis三个版本(3.x,4.x,6.x)对于多线程的使用比对
  • 如何克服编程学习中的挫折感的?
  • redis列表若干记录
  • LeetCode-轮转数组