This guide will walk you through the steps of building a scheduler with genezio. Schedulers are automated systems designed to carry out tasks at set intervals or specific times. They play a crucial role in various applications and automation. Use cases include sending emails, conducting routine database cleanup and database backup, or undertaking data analysis and reporting activities.
Genezio makes things easier for you, so you don’t need any additional npm library like node-cron.
Content
- Prerequisites
- Getting Started
- Setting up your Scheduler
- Test your Scheduler
- Deploy your Scheduler
- Create more complex schedules
- Do’s and Don’ts Tips
- Conclusion
Prerequisites
If you don’t already have them, you’ll need to install the following tools:
Note: I recommend you use
nvm
to manage NodeJs and npm versions. After installing nvm
, you can easily get any node version by running nvm install <node_version>
.
Getting Started
First, you’ll need to create a new project.
To get started with a template, install genezio
using npm
and run it in your terminal. Later on, genezio comes in handy to deploy and host your web applications in the cloud.
npm install -g genezio
After installing genezio
, you can create a new Genezio Node.js project by running the following command in an empty new folder:
genezio create backend --backend=ts --name=scheduler-app --region=us-east-1
cd ./scheduler-app
Setting up your Scheduler
Next, create a new file called scheduler.ts
in the root directory of your project.
Open this newly created file in your preferred IDE and add the following code:
scheduler.ts
import { GenezioDeploy, GenezioMethod } from "@genezio/types";
/**
* This class can be deployed on genezio infrastructure
* using the "genezio deploy" command or tested locally using "genezio local".
*/
@GenezioDeploy()
export class Scheduler {
@GenezioMethod({ type: "cron", cronString: "* * * * *" })
public async everyMinuteTask() {
const output = "Every minute task executed at " + new Date().toISOString();
console.log(output);
}
}
In this example, we’re creating a task function that will execute every minute, logging the current time to the console. The everyMinuteTask
function doesn’t need any parameter, but it is used with the decorator @GenezioMethod({ type: "cron", cronString: "* * * * *" })
with a cron-style schedule string.
The schedule string follows the format * * * * *
, representing minutes, hours, days of the month, months, and days of the week, respectively. An asterisk means “every interval”.
Note 1: I recommend using Crontab Guru to generate and check your cron syntax.
Note 2: You can also use JavaScript for your code. Just change the extension of your file to js
.
Note 3: The crontab syntax is agnostic of the operating system.
Test your Scheduler
With genezio you can test your scheduler locally by running a genezio local server with the following command:
genezio local
The task will run every minute and will print the output in the console of your local genezio web server.
Deploy your Scheduler
Next, the application is ready to be deployed to the cloud to be used in a production environment. To deploy your application, run the following command in the root directory of your project:
genezio deploy
This will deploy the whole project to the cloud and make it run the task every minute. You can continue to manage, test, update and monitor your project from the genezio dashboard .
Note 1: You can deploy your scheduler together with your API Node.js application.
Note 2: Your scheduler will be deployed in a Linux environment.
Create more complex schedulers
Run a task every 10 minutes:
Cron expression: */10 * * * *
scheduler.ts
@GenezioMethod({ type: "cron", cronString: "*/10 * * * *" })
public async every10MinuteTask() {
const output = "Every 10 minutes " + new Date().toISOString();
console.log(output);
}
Run a task every day at 8 AM:
Cron expression: 0 8 * * *
scheduler.ts
@GenezioMethod({ type: "cron", cronString: "0 8 * * *" })
public async everyDay8AMTask() {
const output = "Every day at 8 AM" + new Date().toISOString();
console.log(output);
}
Do’s and Don’ts Tips
Do’s:
- Schedule carefully: Plan your cron schedule jobs carefully, considering factors like resource usage, the frequency of the task, server timezone, and even the 29th of February.
- Monitor and log: Set up monitoring and logging for your cron jobs to receive notifications of any errors or unexpected behavior.
- Use a clear and descriptive comment: Include a comment at the beginning of your cron job to describe its purpose. This makes it easier for you and others to understand what the cron job does.
- Keep it simple: Keep your cron jobs as simple as possible. If a task becomes too complex for a cron job, consider breaking it down into smaller scripts.
Don’ts:
- Overload your system: Avoid scheduling too many cron jobs that run simultaneously or at high frequencies, this can lead to race conditions on your data.
- Forget to test and validate: Never add a cron job without testing it thoroughly first. Errors in cron jobs can disrupt system operations. Another point of failure can be the server timezone and unix timestamp.
- Ignore error handling: Don’t neglect error handling in your cron jobs. Always include proper error-checking mechanisms and consider sending notifications when errors occur.
- Hardcode sensitive data: Avoid hardcoding sensitive information like passwords directly in your scripts. Instead, use environment variables.
- Use JavaScript: Avoid using JavaScript because it can lead to runtime errors. Use TypeScript instead to fix as many type errors as possible.
Conclusion
In conclusion, scheduling tasks with Node.js and Genezio is a powerful and flexible solution for automating various processes in your applications. With the ability to create and manage complex schedules using cron expressions, you can ensure that your scheduled tasks run precisely when needed. However, it’s essential to follow best practices, such as careful scheduling, monitoring, and error handling, to maintain the reliability and efficiency of your scheduled tasks. After this tutorial, you can harness the full potential of Genezio to streamline your workflow and enhance automation in your projects.
I hope you enjoyed this tutorial and I encourage you to check out our other tutorials for more tips and tricks on improving your software engineering skills. 🥷 💻
Also, I invite you to check your examples from GitHub .
Start leveraging the power of Genezio for efficient task scheduling in your applications.
Article contents
Subscribe to our newsletter
Genezio is a serverless platform for building full-stack web and mobile applications in a scalable and cost-efficient way.
Related articles
More from Tutorials