Getting started¶
In five minutes you will have a web application that runs background jobs in its own process, keeps them in PostgreSQL and shows them on a dashboard: a fire-and-forget job, a delayed one and a recurring one.
You need the .NET 10 SDK or later and a PostgreSQL database whose user may create a schema. Bellhop's SQL uses nothing newer than PostgreSQL 12.
Create the project¶
dotnet new web -o MyApp
cd MyApp
dotnet add package Bellhop.PostgreSql --prerelease
dotnet add package Bellhop.Dashboard --prerelease
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:Default" "Host=localhost;Database=app;Username=app;Password=<your password>"
The connection string stays out of your source: user secrets while you develop, your host's secret store or environment in production. Bellhop never logs it.
Each file below goes in MyApp/, at the path named above it. Create the folders as you go.
Program.cs¶
Replace the template's Program.cs with:
// Program.cs
using Bellhop;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddBellhop(bellhop =>
{
bellhop.UsePostgres(builder.Configuration.GetConnectionString("Default")!);
bellhop.AddJobsFromAssemblyContaining<Program>();
bellhop.AddWorker(); // run jobs in this process; also provides IJobClient
});
builder.Services.AddAuthorization(options => options.AddPolicy("Admins", policy => policy.RequireRole("Admins")));
builder.Services.AddApplicationServices(); // your application's own, in Application/ApplicationSetup.cs
var app = builder.Build();
app.MapBellhopDashboard("/jobs").RequireAuthorization("Admins");
app.MapApplicationEndpoints();
app.Run();
That is Bellhop's whole setup. UsePostgres picks the store, AddJobsFromAssemblyContaining registers every job handler in your project, and AddWorker runs jobs in this process and gives you IJobClient to create them. AddApplicationServices and MapApplicationEndpoints are your application's own: a new project needs them, and the rest of your application shows them. In an application you already have, leave them out.
The dashboard at /jobs uses your application's own authorization: RequireAuthorization("Admins") lets in the users the Admins policy accepts, here users in the Admins role, signed in by your application's authentication (here a cookie, below). Outside Development the application does not start with a dashboard that has no authorization requirement, and it does not start with a requirement but no AddAuthorization. The dashboard line is optional; leave it out and jobs run the same. See the dashboard's access rules for view and operate permissions.
The same pieces split across processes when the web tier should never run jobs. Each process registers only what it does, and they meet only in the store:
// Web API: enqueue jobs and serve the dashboard, never run jobs
builder.Services.AddBellhop(bellhop =>
{
bellhop.UsePostgres(connectionString);
bellhop.AddJobsFromAssemblyContaining<Program>();
bellhop.AddClient();
});
app.MapBellhopDashboard("/jobs").RequireAuthorization("Admins");
// Worker service: run jobs, no dashboard
builder.Services.AddBellhop(bellhop =>
{
bellhop.UsePostgres(connectionString);
bellhop.AddJobsFromAssemblyContaining<SendWelcomeEmail>();
bellhop.AddWorker(worker => worker.Queues = ["default", "reports"]);
});
A job and its handler¶
Add Jobs/SendWelcomeEmail.cs:
// Jobs/SendWelcomeEmail.cs
using Bellhop.Attributes;
using Bellhop.Jobs;
[JobName("send-welcome-email")] // stable identity; renaming the class is safe
public sealed record SendWelcomeEmail(Guid UserId) : IJob;
public sealed class SendWelcomeEmailHandler(IEmailSender email) : IJobHandler<SendWelcomeEmail>
{
public Task HandleAsync(SendWelcomeEmail job, JobContext ctx, CancellationToken ct)
=> email.SendWelcomeAsync(job.UserId, ct);
}
A job is a record of data with a stable name; the handler is an ordinary class built by dependency injection for each run. IEmailSender stands for your own email service.
Enqueue and schedule¶
Add RegisterUser.cs:
// Anywhere, via DI
using Bellhop.Jobs;
public sealed class RegisterUser(IJobClient jobs)
{
public async Task RegisterAsync(User user)
{
await jobs.EnqueueAsync(new SendWelcomeEmail(user.Id));
await jobs.ScheduleAsync(new SendFollowUpEmail(user.Id), delay: TimeSpan.FromDays(3));
}
}
EnqueueAsync stores the job for a worker to run as soon as one is free; ScheduleAsync with a delay stores it to run three days from now. Both return once the job is stored.
A recurring job¶
Add Jobs/NightlyCleanup.cs:
// A recurring job, declared where it lives
using Bellhop.Attributes;
using Bellhop.Jobs;
using Bellhop.Scheduling;
[JobName("nightly-cleanup")]
[Recurring("nightly-cleanup", "0 3 * * *", TimeMode = TimeMode.Local, TimeZone = "Europe/Sofia", OverlapPolicy = OverlapPolicy.Skip)]
public sealed record NightlyCleanup : IJob;
Every night at 03:00 in Sofia, with the clock changes handled, a NightlyCleanup job runs; if last night's run is still going, tonight's is skipped. The recurring job needs a handler in your project like any job, or the application does not start.
The rest of your application¶
Bellhop's part is done. The files in this section stand for what an application already has and a new project does not: the job handlers' own work, a user, an email service, a way to sign up and a way to sign in. In an application you already have, use yours instead.
The recurring job's handler, Jobs/NightlyCleanupHandler.cs:
// Jobs/NightlyCleanupHandler.cs
using Bellhop.Jobs;
public sealed class NightlyCleanupHandler : IJobHandler<NightlyCleanup>
{
public Task HandleAsync(NightlyCleanup job, JobContext ctx, CancellationToken ct)
=> Task.CompletedTask; // your cleanup: expired sessions, old files
}
The follow-up that RegisterUser schedules, Jobs/SendFollowUpEmail.cs:
// Jobs/SendFollowUpEmail.cs
using Bellhop.Attributes;
using Bellhop.Jobs;
[JobName("SendFollowUpEmail")]
public sealed record SendFollowUpEmail(Guid UserId) : IJob;
public sealed class SendFollowUpEmailHandler(IEmailSender email) : IJobHandler<SendFollowUpEmail>
{
public Task HandleAsync(SendFollowUpEmail job, JobContext ctx, CancellationToken ct)
=> email.SendFollowUpAsync(job.UserId, ct);
}
The user, Application/User.cs:
The email service the handlers use, which only logs, Application/Email.cs:
// Application/Email.cs
public interface IEmailSender
{
Task SendWelcomeAsync(Guid userId, CancellationToken ct);
Task SendFollowUpAsync(Guid userId, CancellationToken ct);
}
// Stands for your email service: it logs each email instead of sending it.
public sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
{
public Task SendWelcomeAsync(Guid userId, CancellationToken ct)
{
Sending(logger, "welcome", userId);
return Task.CompletedTask;
}
public Task SendFollowUpAsync(Guid userId, CancellationToken ct)
{
Sending(logger, "follow-up", userId);
return Task.CompletedTask;
}
[LoggerMessage(Level = LogLevel.Information, Message = "Sending the {Email} email to user {UserId}.")]
private static partial void Sending(ILogger logger, string email, Guid userId);
}
The services and endpoints that Program.cs adds, Application/ApplicationSetup.cs:
// Application/ApplicationSetup.cs
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
public static class ApplicationSetup
{
private const string SignInPath = "/sign-in";
public static void AddApplicationServices(this IServiceCollection services)
{
services.AddSingleton<IEmailSender, LoggingEmailSender>();
services.AddScoped<RegisterUser>();
// The cookie's challenge sends a signed-out visitor of the dashboard to the LoginPath.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.LoginPath = SignInPath);
}
public static void MapApplicationEndpoints(this WebApplication app)
{
// Stand-ins for your sign-up and sign-in pages, for Development only: anyone who reaches
// /sign-in becomes an Admin, and anyone can register users at /users.
if (!app.Environment.IsDevelopment())
{
return;
}
// Loopback host names only, so a web page cannot reach them by rebinding its own name to this machine.
var standIns = app.MapGroup("").RequireHost("localhost", "127.0.0.1");
standIns.MapPost("/users", async (RegisterUser registration) =>
{
var user = new User(Guid.NewGuid());
await registration.RegisterAsync(user);
return user.Id;
});
// The cookie redirects to RedirectUri after a sign-in only on its LoginPath.
standIns.MapGet(SignInPath, () => Results.SignIn(
new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.Name, "developer"), new Claim(ClaimTypes.Role, "Admins")],
authenticationType: "Development")),
new AuthenticationProperties { RedirectUri = "/jobs" }));
}
}
AddApplicationServices registers the email service and RegisterUser, and signs users in with a cookie. That cookie is what the dashboard needs: RequireAuthorization checks a signed-in user, so /jobs needs your application's authentication. Without AddAuthentication the application starts, and /jobs answers every request with a 500, "Unable to find the required 'IAuthenticationService' service".
MapApplicationEndpoints maps two stand-ins, in the Development environment only, which is where dotnet run runs:
POST /usersregisters a new user throughRegisterUser, as your sign-up would./sign-insigns you in asdeveloper, in the Admins role, and sends you to the dashboard. It is the cookie'sLoginPath, so the dashboard sends you there when you are signed out.
Anyone who can reach /sign-in becomes an Admin. Both stand-ins answer only requests addressed to localhost or 127.0.0.1, so a web page cannot reach them by pointing its own host name at your machine; another machine can send any host name, so keep a Development application on localhost, as the template's launch settings do. In any other environment neither endpoint exists: a signed-out visitor to /jobs is still sent to /sign-in, which must then be your application's own sign-in page. A signed-in user outside the Admins role is sent to /Account/AccessDenied, the cookie's AccessDeniedPath, which is your application's page too.
Run it¶
On its first start the node creates the bellhop schema in your database and logs a summary of what it runs: the store and schema version, the worker's queues, the jobs and recurring jobs, and the dashboard's access rules. The application logs the address it listens on, such as Now listening on: http://localhost:5123; use your port below.
Register a user from another terminal (in Windows PowerShell, type curl.exe):
The application logs "Sending the welcome email to user …" within a second. Then open http://localhost:<port>/jobs in a browser: signed out, it sends you to /sign-in, which signs you in and brings you back. The dashboard shows the welcome email's job, the follow-up scheduled three days out and the recurring job.
Things you did not have to do: create a database schema by hand, choose polling intervals, write an authorization filter class, configure a serializer, register a hosted service, or pin package versions.
Next¶
- Concepts: what Bellhop guarantees, and why your handlers should be idempotent
- Testing your jobs
- Running in production