Skip to content

Instantly share code, notes, and snippets.

@Swimburger
Created April 28, 2023 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swimburger/532e390c9e1b17c700576282cfbf6db7 to your computer and use it in GitHub Desktop.
Save Swimburger/532e390c9e1b17c700576282cfbf6db7 to your computer and use it in GitHub Desktop.
Ad-hoc CRON jobs from a console application with Hangfire
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