Skip to content

Example ASP.NET Core

Leonard Sperry edited this page Aug 14, 2016 · 1 revision

Step by step is an example on how to set up Chroniton to work with your ASP.NET Core website.

  1. First add the Chroniton.NetCore nuget package
  2. Open the startup.cs file in your project.
  3. add using Chroniton; to the top of the file.
  4. Inside the ConfigureServices method, add the following line
    services.AddSingleton<ISingularity, Singularity>(serviceProvider => Singularity.Instance);
  1. Inside the Configure method, add the following
    var singularity = Singularity.Instance;
    singularity.Start();

At this point, Chroniton is now set up and will run with your application starts. The following is a sample controller which will demonstrate Chroniton working.

using Chroniton;
using Chroniton.Jobs;
using Chroniton.Schedules;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace WebApplication1.Controllers
{
    public class ChronitonController : Controller
    {
        readonly ISingularity _singularity;
        static List<string> _messages = new List<string>();

        public ChronitonController(ISingularity singularity)
        {
            _singularity = singularity;
        }

        public string Index()
        {
            if (_messages.Count == 0)
            {
                return "no messages yet";
            }
            return _messages.ToArray().Aggregate((s1, s2) => $"{s1}\r\n{s2}");
        }

        public string Add(string message, int seconds)
        {
            var job = _singularity.ScheduleParameterizedJob(
                new EveryXTimeSchedule(TimeSpan.FromSeconds(seconds))
                , new SimpleParameterizedJob<string>((msg, dt) => _messages.Add($"{dt.ToString()}\t{msg}")),
                message, true);

            //cancel the job in 1 minute
            _singularity.ScheduleJob(new RunOnceSchedule(TimeSpan.FromMinutes(1)),
                new SimpleJob(dt => _singularity.StopScheduledJob(job)), false);

            return "added";
        }
    }
}

Please note that the above code has very little error checking, and it's recommended to create your own implementations of jobs instead of using the SimpleJob. This is only example code.

When you navigate to ~chroniton it will render no messages yet. To see it working navigate to:

~chroniton/add?message=1st message&seconds=2. Now you can go to ~chroniton and see the it in action. By refreshing the page, you'll see more messages added to the list.

Clone this wiki locally