Created
April 28, 2023 21:22
-
-
Save Swimburger/532e390c9e1b17c700576282cfbf6db7 to your computer and use it in GitHub Desktop.
Ad-hoc CRON jobs from a console application with Hangfire
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 Hangfire; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddHangfire(configuration => configuration | |
.UseSimpleAssemblyNameTypeSerializer() | |
.UseRecommendedSerializerSettings() | |
.UseInMemoryStorage()); | |
builder.Services.AddHangfireServer(); | |
var app = builder.Build(); | |
// host dashboard at "/" | |
app.MapHangfireDashboard(""); | |
await app.StartAsync(); | |
var cts = new CancellationTokenSource(); | |
var ct = cts.Token; | |
while (!ct.IsCancellationRequested) | |
{ | |
Console.WriteLine("Enter a command:"); | |
var command = Console.ReadLine(); | |
switch (command) | |
{ | |
case "?": | |
Console.WriteLine("Commands:"); | |
Console.WriteLine(" ? - show this help"); | |
Console.WriteLine(" q - quit"); | |
Console.WriteLine(" s - schedule a job"); | |
Console.WriteLine(" r - remove a job"); | |
break; | |
default: | |
Console.WriteLine("Unknown command: " + command); | |
goto case "?"; | |
case "q": | |
cts.Cancel(); | |
break; | |
case "s": | |
{ | |
Console.WriteLine("Enter a schedule:"); | |
var schedule = Console.ReadLine(); | |
Console.WriteLine("Enter an ID:"); | |
var id = Console.ReadLine(); | |
RecurringJob.AddOrUpdate( | |
id, | |
() => Console.WriteLine("Ahoy!"), | |
schedule | |
); | |
break; | |
} | |
case "r": | |
{ | |
Console.WriteLine("Enter an ID:"); | |
var id = Console.ReadLine(); | |
RecurringJob.RemoveIfExists(id); | |
break; | |
} | |
} | |
} | |
await app.StopAsync(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment