TickerNet docs Sponsored by Omniscient AI

TickerNet · using it

Getting started

From an empty .NET 10 or .NET 11 app to scheduled jobs, a database store and a live dashboard. Every API name, option and default on this page comes from the code in src/ and samples/.

On this page
  1. Requirements
  2. Add the packages
  3. Register TickerNet
  4. Write a job
  5. Schedule jobs
  6. Choose a store
  7. Dashboard
  8. Logs and tracing
01

Requirements

  • .NET 10 or .NET 11. Every package has a net10.0 and a net11.0 build. Each uses the Microsoft.Extensions and EF Core packages of its own .NET version: [10.0.0,11.0.0) on .NET 10, [11.0.0,12.0.0) on .NET 11 (ADR 0012).
  • ASP.NET Core, for the dashboard. TickerNet.Dashboard references the Microsoft.AspNetCore.App framework. The scheduler itself also runs in a console app or worker service.
  • A store, if jobs must survive a restart. An EF Core relational database provider (the samples and tests use SQLite), Redis, or MongoDB.
  • Node.js LTS, only to build the dashboard from source. Its web app is built into wwwroot/dist and embedded in the assembly.
Job code in another process? This page sets up jobs that run in the scheduler's own process. To run them in separate worker apps that connect to the scheduler, add TickerNet.Hub and TickerNet.Worker as Remote workers shows, after you have the basics below working.
02

Add the packages

The packages are on nuget.org. You can also build from source and use project references, as the samples do.

  1. Add them from NuGet. Add the core package, one store, and the dashboard if you want it.
    shellnuget.org
    dotnet add package TickerNet
    dotnet add package TickerNet.EntityFrameworkCore   # or .Caching.StackExchangeRedis, .MongoDB
    dotnet add package TickerNet.Dashboard
    The source generator comes inside TickerNet. Keep every TickerNet package on the same version.
  2. Or build from source. To work on TickerNet itself, or to try an unreleased change, clone and build it. The core package takes the source generator from the generator's bin/ folder, so build the generator first. Build the dashboard's web app too if you want the dashboard.
    shellfrom CONTRIBUTING.md
    git clone https://github.com/TickerNet/TickerNet.git
    cd TickerNet
    (cd src/TickerNet.Dashboard/wwwroot && npm ci && npm run build)
    dotnet build src/TickerNet.SourceGenerator/TickerNet.SourceGenerator.csproj -c Release
    dotnet build TickerNet.slnx -c Release
  3. Reference the projects (source builds only). A project reference to TickerNet does not bring the source generator with it (the generator DLL is only added when the package is packed), so reference the generator as an analyzer too. Add only the store and dashboard projects you use.
    YourApp.csprojpattern from samples/*/*.csproj
    <ItemGroup>
      <ProjectReference Include="..\TickerNet\src\TickerNet\TickerNet.csproj" />
      <ProjectReference Include="..\TickerNet\src\TickerNet.SourceGenerator\TickerNet.SourceGenerator.csproj"
                        OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
    
      <!-- Optional -->
      <ProjectReference Include="..\TickerNet\src\TickerNet.EntityFrameworkCore\TickerNet.EntityFrameworkCore.csproj" />
      <ProjectReference Include="..\TickerNet\src\TickerNet.Dashboard\TickerNet.Dashboard.csproj" />
    </ItemGroup>
    Building src/ also writes .nupkg files, because src/Directory.Build.props sets GeneratePackageOnBuild. You can put those in a local NuGet feed instead.
03

Register TickerNet

Two calls: AddTickerNet on the service collection and UseTickerNet on the built host.

src/TickerNet/DependencyInjection/TickerNetServiceExtensions.cssignatures
public static IServiceCollection AddTickerNet(this IServiceCollection services,
    Action<TickerOptionsBuilder<TimeTickerEntity, CronTickerEntity>> optionsBuilder = null)

public static IServiceCollection AddTickerNet<TTimeTicker, TCronTicker>(this IServiceCollection services,
    Action<TickerOptionsBuilder<TTimeTicker, TCronTicker>> optionsBuilder = null)
    where TTimeTicker : TimeTickerEntity<TTimeTicker>, new()
    where TCronTicker : CronTickerEntity, new()

public static IHost UseTickerNet(this IHost host, TickerNetStartMode qStartMode = TickerNetStartMode.Immediate)

Use the generic form when you derive your own entity types from TimeTickerEntity<T> and CronTickerEntity. WebApplication is an IHost, so web apps call app.UseTickerNet(); worker services call host.UseTickerNet().

Call UseTickerNet() before the host runs. It tells TickerNet to start up when the host starts: build the function list, seed cron jobs, run your seeders, and run the store's startup step. Tools that build the host without starting it, such as EF Core migrations, trigger none of this. If you forget the call, startup is skipped and TickerNet logs a warning that starts TickerNet — UseTickerNet() was not called.

With TickerNetStartMode.Manual the scheduler does not start with the host. Start it yourself through ITickerNetHostScheduler.StartAsync().

Program.csoptions example
using TickerNet.DependencyInjection;

builder.Services.AddTickerNet(options =>
{
    options.ConfigureScheduler(scheduler =>
    {
        scheduler.MaxConcurrency = 8;
        scheduler.SchedulerTimeZone = TimeZoneInfo.Utc;
    });
    options.SetExceptionHandler<MyTickerExceptionHandler>();   // implements ITickerExceptionHandler
});

Scheduler settings

Set these inside ConfigureScheduler. They live on SchedulerOptionsBuilder in src/TickerNet.Utilities/TickerOptionsBuilder.cs.

SettingDefaultWhat it does
NodeIdentifierEnvironment.MachineNameThis node's name. It is written as the lock holder on jobs the node takes, and used for heartbeats.
MaxConcurrencyEnvironment.ProcessorCountNumber of worker threads that run jobs.
IdleWorkerTimeOut1 minuteHow long an idle worker thread waits before it stops.
MinPollingInterval1 secondShortest wait between two reads of the store. Also settable as options.MinPollingInterval.
FallbackIntervalChecker30 secondsHow often a second service looks for jobs that are past due and still waiting.
StaleCronOccurrenceThresholdTimeSpan.Zero (off)Set by SkipStaleCronOccurrencesOnStartup(), below.
SchedulerTimeZoneTimeZoneInfo.LocalTime zone for cron expressions, and for execution times given with DateTimeKind.Unspecified.

Options builder methods

MethodWhat it does
UseGZipCompression()Compress request payloads with GZip. Without it they are stored as plain UTF-8 JSON.
ConfigureRequestJsonOptions(Action<JsonSerializerOptions>)JSON settings for request payloads.
WithJsonContext(IJsonTypeInfoResolver)Use a source-generated JSON context for payloads, for Native AOT or trimming.
SkipStaleCronOccurrencesOnStartup(TimeSpan? threshold = null)At startup, mark waiting cron runs that are further in the past than the threshold (5 seconds if not given) as Skipped, so a restart doesn't run them late.
IgnoreSeedDefinedCronTickers()Don't create cron jobs from cron expressions in [TickerFunction] at startup. They are created by default.
UseTickerSeeder(...)Run your own code at startup with the time manager, the cron manager, or both, to create jobs.
DisableBackgroundServices()Register only the managers. This app adds jobs; another app runs them.
SetExceptionHandler<THandler>()Call your ITickerExceptionHandler when a job fails or is cancelled.
EnableActivitySource()Emit OpenTelemetry spans. See Logs and tracing.
04

Write a job

A job is a method with [TickerFunction]. The function name is how you schedule it.

src/TickerNet.Utilities/Base/TickerFunctionAttribute.csconstructors
public TickerFunctionAttribute(string functionName, string cronExpression = null,
    TickerTaskPriority taskPriority = TickerTaskPriority.Normal, int maxConcurrency = 0)

public TickerFunctionAttribute(string functionName, TickerTaskPriority taskPriority, int maxConcurrency = 0)
ReportJobs.csexample
using TickerNet.Utilities.Base;

public record ReportRequest(int CustomerId, string Format);

public class ReportJobs
{
    private readonly ILogger<ReportJobs> _logger;

    public ReportJobs(ILogger<ReportJobs> logger) => _logger = logger;

    // Runs whenever you schedule "BuildReport". The payload arrives typed.
    [TickerFunction("BuildReport")]
    public Task BuildAsync(TickerFunctionContext<ReportRequest> context, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Report for {CustomerId} as {Format}, attempt {Retry}",
            context.Request.CustomerId, context.Request.Format, context.RetryCount);
        return Task.CompletedTask;
    }

    // Also creates a cron job at startup: 02:00:00 every day.
    [TickerFunction("NightlyCleanup", "0 0 2 * * *")]
    public Task CleanupAsync(TickerFunctionContext context, CancellationToken cancellationToken)
        => Task.CompletedTask;
}
  • Parameters. A job method can take TickerFunctionContext, TickerFunctionContext<T>, a CancellationToken, or nothing. The context gives Id, ParentId, Type, RetryCount, IsDue, ScheduledFor (UTC) and FunctionName, and RequestCancellation(). For cron runs, context.CronOccurrenceOperations.SkipIfAlreadyRunning() stops this run if another run of the same cron job is still going.
  • The class. It must be a top-level, non-abstract, public or internal class. Each attempt runs in a new dependency injection scope, and the generated code builds the class with its constructor parameters taken from that scope (keyed services via [FromKeyedServices] work too). If the class has several constructors, mark one with [TickerNetConstructor]. Static methods need no instance.
  • Cron syntax. Six fields, seconds first: second minute hour day month day-of-week. A value such as "%Jobs:CleanupCron%" is read from configuration at startup instead.
  • Mistakes show at build time. The generator reports diagnostics TN001 to TN011 for problems such as a missing or duplicate name, a bad cron expression or a wrong parameter type. See the full list.

Register jobs in code instead

Classes that implement ITickerFunction or ITickerFunction<TRequest>, and plain lambdas, can be registered with MapTicker. A class's function name is its type name; a group adds a prefix, as in Orders.ProcessOrderJob. This is the pattern in samples/TickerNet.Sample.Dashboard.ReflectionFree.

Program.csfrom samples/TickerNet.Sample.Dashboard.ReflectionFree
builder.Services.MapTickerGroup("Background", group =>
{
    group.MapTicker<CleanupJob>()
        .WithCron("0 0 * * * *")
        .WithMaxConcurrency(1);
});

builder.Services.MapTickerGroup("Orders")
    .WithMaxConcurrency(5)
    .MapTicker<ProcessOrderJob, OrderRequest>();

builder.Services.MapTicker("InlinePing", (ctx, ct) =>
{
    Console.WriteLine($"Ping! Id={ctx.Id}");
    return Task.CompletedTask;
});
05

Schedule jobs

Inject ITimeTickerManager<TimeTickerEntity> for one-off jobs and ICronTickerManager<CronTickerEntity> for recurring ones.

src/TickerNet.Utilities/Interfaces/Managers/ITimeTickerManager.csabridged
public interface ITimeTickerManager<TTimeTicker> where TTimeTicker : TimeTickerEntity<TTimeTicker>
{
    Task<TickerResult<TTimeTicker>> AddAsync(TTimeTicker entity, CancellationToken cancellationToken = default);
    Task<TickerResult<TTimeTicker>> UpdateAsync(TTimeTicker timeTicker, CancellationToken cancellationToken = default);
    Task<TickerResult<TTimeTicker>> DeleteAsync(Guid id, CancellationToken cancellationToken = default);
    // AddBatchAsync, UpdateBatchAsync, DeleteBatchAsync, and AddAsync<TFunction> for MapTicker classes
}
ReportScheduler.csexample
using TickerNet.Utilities;
using TickerNet.Utilities.Entities;
using TickerNet.Utilities.Interfaces.Managers;

public class ReportScheduler(
    ITimeTickerManager<TimeTickerEntity> timeTickers,
    ICronTickerManager<CronTickerEntity> cronTickers)
{
    public async Task ScheduleAsync(CancellationToken ct)
    {
        // Once, in ten minutes, with a payload and three retries.
        var once = await timeTickers.AddAsync(new TimeTickerEntity
        {
            Function = "BuildReport",
            ExecutionTime = DateTime.UtcNow.AddMinutes(10),
            Request = TickerHelper.CreateTickerRequest(new ReportRequest(42, "pdf")),
            Retries = 3,
            RetryIntervals = [30, 60, 300]   // seconds; the last value repeats
        }, ct);

        if (!once.IsSucceeded)
            throw once.Exception;

        // Every Monday at 08:00:00, in the scheduler's time zone.
        await cronTickers.AddAsync(new CronTickerEntity
        {
            Function = "BuildReport",
            Expression = "0 0 8 * * 1",
            Request = TickerHelper.CreateTickerRequest(new ReportRequest(42, "pdf"))
        }, ct);
    }
}
  • Results, not exceptions. Manager methods return a TickerResult<T> with IsSucceeded, Result, Exception and AffectedRows. An unknown function name or a cron expression that doesn't parse comes back as a failed result.
  • Execution time. No ExecutionTime means now. UTC and local times are converted to UTC; a time with DateTimeKind.Unspecified is read in SchedulerTimeZone. A job due within the next second is handed straight to the workers instead of waiting for the scheduler loop. It then runs with the host's lifetime, not the CancellationToken you passed, so the end of an HTTP request doesn't cancel it.
  • Retries. Retries is the number of extra attempts. RetryIntervals gives the wait before each one in seconds; without it each wait is 30 seconds.

Chained jobs

FluentChainTickerBuilder<TTimeTicker> (in TickerNet.Utilities.Managers) builds a parent job with up to five children, each with up to five grandchildren. Each child has a RunCondition: OnSuccess, OnFailure, OnCancelled, OnFailureOrCancelled, OnAnyCompletedStatus or InProgress (runs alongside the parent).

examplepattern from benchmarks/TickerNet.Benchmarks/ChainBuilderBenchmarks.cs
var chain = FluentChainTickerBuilder<TimeTickerEntity>.BeginWith(p => p
        .SetFunction("ImportFile")
        .SetExecutionTime(DateTime.UtcNow.AddMinutes(1)))
    .WithFirstChild(c => c
        .SetFunction("NotifyImportDone")
        .SetRunCondition(RunCondition.OnSuccess))
    .WithSecondChild(c => c
        .SetFunction("NotifyImportFailed")
        .SetRunCondition(RunCondition.OnFailure))
    .Build();

await timeTickers.AddAsync(chain);
06

Choose a store

Jobs stay in memory unless you add a store inside AddTickerNet(options => ...).

In memory (the default)

If no store is added, AddTickerNet registers TickerInMemoryPersistenceProvider. Jobs live in the process and are gone when it stops, so use it for development, tests or jobs you can lose.

Entity Framework Core

AddOperationalStore from TickerNet.EntityFrameworkCore.DependencyInjection takes a TickerNetEfCoreOptionBuilder. Pick one of two ways.

TickerNet's own DbContextfrom samples/TickerNet.Sample.WebApi
using Microsoft.EntityFrameworkCore;
using TickerNet.EntityFrameworkCore.DbContextFactory;
using TickerNet.EntityFrameworkCore.DependencyInjection;

builder.Services.AddTickerNet(options =>
{
    options.AddOperationalStore(ef =>
    {
        ef.UseTickerNetDbContext<TickerNetDbContext>(db =>
            db.UseSqlite("Data Source=tickernet.db"));
    });
});
Your own DbContextfrom samples/TickerNet.Sample.ApplicationDbContext
using TickerNet.EntityFrameworkCore.Customizer;

builder.Services.AddDbContext<AppDbContext>(db => db.UseSqlite("Data Source=app.db"));

builder.Services.AddTickerNet(options =>
{
    options.AddOperationalStore(ef =>
    {
        ef.UseApplicationDbContext<AppDbContext>(ConfigurationType.UseModelCustomizer);
    });
});
  • UseTickerNetDbContext<TDbContext>(Action<DbContextOptionsBuilder> optionsAction, string schema = null) registers a pooled context factory. The pool holds 1024 contexts unless you call SetDbContextPoolSize.
  • UseApplicationDbContext<TDbContext>(ConfigurationType) stores jobs in your context. UseModelCustomizer adds TickerNet's three entities to your model for you. With IgnoreModelCustomizer, apply them yourself in OnModelCreating with the public TimeTickerConfigurations<T>, CronTickerConfigurations<T> and CronTickerOccurrenceConfigurations<T> from TickerNet.EntityFrameworkCore.Configurations.
  • The tables are TimeTickers, CronTickers and CronTickerOccurrences in schema ticker. Change the schema with SetSchema(...) or the schema argument.
  • TickerNet doesn't create the tables. Add an EF Core migration for the context and apply it, as the samples do with db.Database.Migrate().

Redis

Program.csRedis
using TickerNet.Caching.StackExchangeRedis.DependencyInjection;

builder.Services.AddTickerNet(options =>
{
    options.AddStackExchangeRedis(redis =>
    {
        redis.Configuration = builder.Configuration.GetConnectionString("Redis");
    });
});
  • The setup action is required and must set Configuration, ConfigurationOptions, ConnectionMultiplexer or ConnectionMultiplexerFactory. Otherwise AddTickerNet throws InvalidOperationException.
  • TickerNetRedisOptionBuilder extends RedisCacheOptions. It adds NodeHeartbeatInterval (1 minute), ConnectionMultiplexer (yours to dispose) and JsonSerializerContext (for AOT). InstanceName defaults to "tickernet:".
  • Used alone, Redis is the store. Used with the EF Core or MongoDB store, that store keeps the jobs and Redis adds node heartbeats and dead-node cleanup, plus a cache of cron expressions for EF Core.

MongoDB

Program.csfrom samples/TickerNet.Sample.MongoDB
using TickerNet.MongoDB.DependencyInjection;

builder.Services.AddTickerNet(options =>
{
    options.AddOperationalStore(mongo =>
    {
        mongo.UseTickerNetMongoClient(
            connectionString: builder.Configuration["Mongo:ConnectionString"] ?? "mongodb://localhost:27017",
            databaseName: builder.Configuration["Mongo:Database"] ?? "tickernet");
    });
});
  • Call UseTickerNetMongoClient(connectionString, databaseName) to let TickerNet own the client, or UseExistingMongoClient(databaseName) to use an IMongoClient already in dependency injection. If you call neither, AddOperationalStore throws InvalidOperationException.
  • Collections are ticker_TimeTickers, ticker_CronTickers and ticker_CronTickerOccurrences. Change the prefix with SetCollectionPrefix(...). A hosted service creates the indexes at startup.
07

Dashboard

Add TickerNet.Dashboard and call AddDashboard. UseTickerNet() then serves it.

Program.csdashboard with basic sign-in
using TickerNet.Dashboard.DependencyInjection;

builder.Services.AddTickerNet(options =>
{
    options.AddDashboard(dashboard =>
    {
        dashboard.SetBasePath("/jobs");
        dashboard.WithBasicAuth("admin", builder.Configuration["Dashboard:Password"]!);
    });
});

var app = builder.Build();
app.UseTickerNet();   // maps the dashboard at /jobs
app.Run();
  • Path. The default is /tickernet/dashboard. Under it are the web app, the HTTP API at api/... and the SignalR hub at ticker-notification-hub.
  • Hosting. With WebApplication, UseTickerNet() adds the dashboard. With a Startup class, a startup filter registered by AddDashboard adds it.
  • From source. The dashboard serves the files embedded from src/TickerNet.Dashboard/wwwroot/dist. Run npm ci && npm run build in wwwroot before you build the project.
Sign-in methodWhat it does
WithNoAuth()No sign-in, on purpose. With no sign-in method at all, the dashboard is also open, but TickerNet logs a warning at startup; this call confirms it and silences the warning.
WithBasicAuth(username, password)Username and password, sent as HTTP Basic.
WithApiKey(apiKey)A key the user enters, sent as a Bearer token.
WithHostAuthentication(policy = null)Your app's own authentication, with an optional authorization policy name.
WithCustomAuth(Func<string, bool> validator)Your function decides. It gets the Authorization header value, or the access_token query value for SignalR.
WithSessionTimeout(minutes)How long a sign-in lasts in the browser. When it runs out, the dashboard forgets the stored credentials and asks again, even in an open tab. The default is 60 minutes; the minimum is 1.

Also on DashboardOptionsBuilder: SetCorsPolicy(...), SetBackendDomain(...), SetGroupName(...) for an OpenAPI group, and the PreDashboardMiddleware, CustomMiddleware and PostDashboardMiddleware hooks.

CORS. Without SetCorsPolicy(...), the dashboard accepts only same-origin requests, which is all its own web app needs. If you use SetBackendDomain(...) and no policy, it allows any origin with credentials so a separately hosted front end keeps working, and logs a warning; set a policy that names the origins that serve the dashboard.

Lock it down before you deploy. Out of the box the dashboard has no sign-in: anyone who can reach the URL can see, add, run and delete jobs. TickerNet logs a warning at startup until you pick a sign-in method or call WithNoAuth().
08

Logs and tracing

Logs. Job events always go to ILogger, with messages such as TickerNet Job completed: {Function} ({JobId}) in {ExecutionTime}ms. Logger categories follow the TickerNet.* namespaces, so Logging:LogLevel:TickerNet in configuration controls them.

Traces. Turn on spans in one of two ways. Both use an ActivitySource named TickerNet.

  • options.EnableActivitySource(), built into the core packages.
  • options.AddOpenTelemetryInstrumentation() from TickerNet.Instrumentation.OpenTelemetry, which also brings in the OpenTelemetry packages.
Program.cstracing
using OpenTelemetry.Trace;

builder.Services.AddTickerNet(options => options.EnableActivitySource());

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource("TickerNet"));   // then add your exporter

Each run is a span named tickernet.job.execute.timeticker or tickernet.job.execute.crontickeroccurrence. Events such as tickernet.job.enqueued, .completed, .failed, .cancelled and .skipped are separate spans. Tags start with tickernet.job., for example tickernet.job.id and tickernet.job.function.