Skip to main content

Cron-Job

Cron Jobs allow you to automate specific commands or scripts on your server to complete repetitive tasks automatically. This can be a very resourceful tool as a Cron Job can be set to run by specific minute or hourly increments, a day of the week or month, or any combination of these.

We also introduced a simple cron job for our project that send request to next.js API and do simple job inside there.

Creating new API endpoint

In pages/api folder create your API endpoint like this.

pages/api/task/example.ts
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
res.status(200).json({ success: "true" });
} catch (err) {
res.status(500).end();
}
}

GitHub Actions makes it easy to automate all your software workflows. So we use github action to run the scheduled cron job automatically. Let's define github action in root folder ./github/workflows/cron.yml like below:

.github/workflows/cron.yml
name: Hourly cron job
on:
schedule:
- cron: "*/60 * * * *"
jobs:
cron:
runs-on: ubuntu-latest
steps:
- name: Hourly cron job
run: |
curl --request POST \
--url 'https://demo.staging.cella.cloud/api/task/example' \
--header 'secret_key: ${{ secrets.SECRET_KEY }}'

Then, once you deploy the application, it will be executed automatically and will execute the cron job every 1 hour and it will send request to the API link what we made above.