Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Fri Feb 23 2024

Creating a scheduler decorator in TypeScript

I recently implemented a feature in a Java Spring boot application, where I run a function every 5 minutes and execute some business logic and publish the result through a web socket. Read more about a similar feature on this guide. Anyway, I was using a built in annotation in Spring called @Scheduled, where I could just annotate my function that I wanted to run every 5th minute and let the framework handle the logic - pretty neat.

And my latest obsession, has been Decorators in TypeScript 5 - and I thought that we could create a similar function that we could use in our TypeScript projects - so in this (short) guide, we will create such a function 🎉.

Task

The task is, to create a decorator that will make our function that are decorated with the @Schedule decorator to be executed at a fixed rate. When we are done, the result should be something like this:

class Executor { @Scheduled(1000) execute() { // Business logic console.log(`Executing at ${new Date().toISOString()}`); } }

and then the exectute() function should run every second i this case.

Implementation

The implementation for this is very simple. We will just create a method decorator that will trigger a setInterval with the provided interval.

function Scheduled(interval: number) { return function (target: any, context: any) { setInterval(() => { target.call(context); }, interval); }; }

More user friendly

If we want to make it a little bit more scalable, we can add some units to the decorator as well, so we don't have to add a massive number if we want longer intervals.

So let's create some types:

enum Unit { MILLISECOND = 1, SECOND = 1000, MINUTE = 60000, HOUR = 3600000, } type ScheduleConfig = { interval: number; unit: Unit };

and then we change the decorator as following:

function Scheduled({ interval, unit }: ScheduleConfig) { return function (target: any, context: any) { setInterval(() => { target.call(context); }, interval * unit); }; }

and call it like this:

class Executor { @Scheduled({ interval: 1, unit: Unit.MINUTE }) execute() { // Business logic console.log(`Executing at ${new Date().toISOString()}`); } }

A little bit more sleek I would say 🤓

Try the code

And to run the code, simply import the class into your main file and create an instance of Executor and it will automatically run, since the decorator are called on the creation of the class, so no need to call the execute() function yourself.

import { Executor } from "./Scheduled"; new Executor();
Executing at 2024-02-23T12:38:19.044Z Executing at 2024-02-23T12:38:20.045Z Executing at 2024-02-23T12:38:21.047Z Executing at 2024-02-23T12:38:22.047Z

Summary

All right, there we have it. A very short tutorial on how we can utilize decorators to create a scheduled function using setInterval. I hope you enjoyed this one, and if you like decorators as much as me, please have a look below on more examples of our tutorials 😃

signatureFri Feb 23 2024
See all our articles