开发环境
- Windows 10 WSL2
- Ubuntu 22.04
- DotNet 6
- Quartz.Net
代码实战
- 新建dotnet项目,添加引用Quartz.net包
入口程序:
static void Main(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
//Serilog
var 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(); }
//Linux
if (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 key
string jobName = typeof(T).Name;
// Try and load the schedule from configuration
var configKey = $"Quartz:{jobName}";
var cronSchedule = config[configKey];
// Some minor validation
if (string.IsNullOrEmpty(cronSchedule))
{
throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
}
// register the job as before
var 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 * * * * ?"
}
}
- 新建.service文件,用作linux服务配置
[Unit]
Description=BPM.JobMgr service
[Service]
# The systemd service file must be configured with Type=notify to enable notifications.
Type=notify
# will set the Current Working Directory (CWD). Worker service will have issues without this setting
WorkingDirectory=/srv
# systemd will run this executable to start the service
ExecStart=/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 environment variable is necessary when dotnet isn't loaded for the specified user.
# To figure out this value, run 'env | grep DOTNET_ROOT' when dotnet has been loaded into your shell.
Environment=DOTNET_ROOT=/usr/share/dotnet/dotnet
# This gives time to MyService to shutdown gracefully.
TimeoutStopSec=300
[Install]
WantedBy=multi-user.target
-
windows10安装WSL2,建议选用Ubuntu 22.04版本方便启用systemd。WSL2安装dotnet6 runtime。
https://learn.microsoft.com/zh-cn/windows/wsl/systemdhttps://learn.microsoft.com/zh-cn/dotnet/core/install/linux-ubuntu-install?tabs=dotnet8&pivots=os-linux-ubuntu-2204#ubuntu-2204
-
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
- 执行效果