Skip to content

Instantly share code, notes, and snippets.

@gistlyn
Last active September 3, 2024 02:34
Show Gist options
  • Save gistlyn/48f3ed8ce823b7405b11f652cfb31dde to your computer and use it in GitHub Desktop.
Save gistlyn/48f3ed8ce823b7405b11f652cfb31dde to your computer and use it in GitHub Desktop.
jobs
dotnet add package ServiceStack.Jobs
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