Job background workers
Job workers lets you schedule background worker functions as recurring cron
jobs or as one-time runAt
jobs. When a job event triggers, your function is called accordingly.
Cron jobs
Example cron jobhook
The example job worker function prints to the log each time the cron triggers.
import app from 'codehooks-js'
app.job('* * * * *', minute)
app.job('*/30 * * * *', halfPast);
function minute(req, res){
console.log("Each minute");
res.end(); // done
}
function halfPast(req, res){
console.log("Each half hour");
res.end(); // done
}
export default app.init();
Utility to create CRON expressions https://crontab.guru/
- Running jobs are stopped and re-started on each deployment (
coho deploy
) - Running jobs are stopped on undeployment (
coho undeploy
)
Cron Syntax
Quick reference to cron syntax.
┌────────────── second (optional) 0-59
│ ┌──────────── minute 0-59
│ │ ┌────────── hour 0-23
│ │ │ ┌──────── day of month 1-13
│ │ │ │ ┌────── month 1-12
│ │ │ │ │ ┌──── day of week 0-7 (0 or 7 are sunday)
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *
Example cron expressions
Run five minutes after midnight, every day
5 0 * * *
Run at 2:15pm on the first of every month
15 14 1 * *
Run at 10 pm on weekdays
0 22 * * 1-5
Schedule delayed worker function dynamically with runAt
Cron jobs are declare at deploy-time and they run forever, or until they are changed or removed by a new deployment.
The schedule.runAt
API is another way to create a one time job that is executed by a worker function.
Example runAt scheduled worker function
The example worker function prints the data payload to the log each time the scheduled datetime triggers.
/*
* runAt example.
*/
import {app, schedule} from 'codehooks-js'
app.worker('myworker', (data, job) => {
const {payload} = data.body
console.log('Delayed job', payload)
job.end()
})
// REST hook
app.get('/hello', async (req, res) => {
const when = new Date(Date.now() + 5000)
const data = {"message": "Hello later!"}
const worker = 'myworker'
await schedule.runAt(when, data, worker)
res.end()
});
// bind to serverless runtime
export default app.init()
If we call the /hello
API the coho logs
command will display the following:
dev 2023-03-23T17:37:54.198Z Delayed job {
"message": "Hello later!"
}
dev 2023-03-23T17:37:54.940Z Delayed job {
"message": "Hello later!"
}
dev 2023-03-23T17:37:55.652Z Delayed job {
"message": "Hello later!"
}
...
Schedule worker function to run immediate
You can also execute a worker function without any delay like this:
...
schedule.run({data}, 'myworker')
...