Automations

From SocialStack

Automations are a mechanism in SocialStack to create a task which runs on some defined schedule. They're also known as "background jobs" or "daemons". The schedule is defined using a cron expression.

Usage[edit | edit source]

First, install the Automations module:

socialstack install Api/Automations

That adds the Events.Automation method to your project, which can then be used like so:

using Api.Automations; // for AutomationRunInfo 

..

// If your automation doesn't need to do anything async:
Events.Automation("once_a_second", "* * * * * ? *")
	.AddEventListener((Context context, AutomationRunInfo info) => {

		System.Console.WriteLine("- Runs once a second -");

		return new ValueTask<AutomationRunInfo>(info);

	});

// With async:
Events.Automation("once_a_second", "* * * * * ? *")
	.AddEventListener(async (Context context, AutomationRunInfo info) => {

		System.Console.WriteLine("- Runs once a second -");
		
		await _someOtherService.DoSomething(context);
		
		return info;

	});

Note that Automation has two args - a name and a schedule. The name is such that your automation can be triggered by hand separately, for example if you need a background job to run "now" rather than waiting for the schedule to trigger it.

Because of the name, it is also possible to add additional handlers to a particular job run. For example if you know a job is called "update_certificate" then you can add an additional handler to the event like so:

Events.Automation("update_certificate")
	.AddEventListener((Context context, AutomationRunInfo info) => {

		System.Console.WriteLine("- This runs immediately after the update_certificate automation. -");

		return new ValueTask<AutomationRunInfo>(info);

	}, 11); // Priority 11 ensures we for certain will happen after the main automations listener(s) occur.

This however is not entirely ideal as it doesn't allow for code completion/ IntelliSense, so if you do suspect that other people will want to tailgate your automation, consider defining an event instead then dispatch it at the end of your automation. This has the advantage of being able to pass specific and potentially useful information about the automation run to followup handlers too.

Usage tips[edit | edit source]

  • Online cron expression editors can help you get the expression you need. NOTE: when selecting a cron formater, use one that supports 7 fields (i.e. seconds resolution), such as this one. A 6 field cron will result in an incomplete expression.
  • The time is always in UTC, meaning it is not affected by local timezone changes such as daylight savings and it is easier to sync larger jobs within a global cluster.