Created
October 8, 2025 09:55
-
-
Save gistlyn/3524a47f6a6911820ba68a62d58a7a66 to your computer and use it in GitHub Desktop.
db-jobs
This file contains hidden or 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.Server |
This file contains hidden or 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 DatabaseJobFeature { | |
| // NamedConnection = "<alternative db>" | |
| }); | |
| 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