Last active
September 3, 2024 02:34
-
-
Save gistlyn/48f3ed8ce823b7405b11f652cfb31dde to your computer and use it in GitHub Desktop.
jobs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dotnet add package ServiceStack.Jobs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using ServiceStack.Data; | |
using ServiceStack.Jobs; | |
using ServiceStack.Web; | |
[assembly: HostingStartup(typeof(MyApp.ConfigureBackgroundJobs))] | |
namespace MyApp; | |
public class ConfigureBackgroundJobs : IHostingStartup | |
{ | |
public void Configure(IWebHostBuilder builder) => builder | |
.ConfigureServices(services => { | |
services.AddPlugin(new CommandsFeature()); | |
services.AddPlugin(new BackgroundsJobFeature()); | |
services.AddHostedService<JobsHostedService>(); | |
}).ConfigureAppHost(afterAppHostInit: appHost => { | |
var services = appHost.GetApplicationServices(); | |
var jobs = services.GetRequiredService<IBackgroundJobs>(); | |
// Example of registering a Recurring Job to run Every Hour | |
//jobs.RecurringCommand<MyCommand>(Schedule.Hourly); | |
}); | |
} | |
public class JobsHostedService(ILogger<JobsHostedService> log, IBackgroundJobs jobs) : BackgroundService | |
{ | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
await jobs.StartAsync(stoppingToken); | |
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(3)); | |
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) | |
{ | |
await jobs.TickAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment