Job Scheduler (Cron)
Having regular jobs running in the background is a common use case. These are isolated scripts that run at regular intervals, for the purpose of automating tasks. Marblism utilizes the node-cron
package to make the experience of implementing such functionality seamless.
You must select the Job Scheduler (Cron)
module during the project creation
Say you have an app where users are required to verify their phone number before registering. Once a user registers on your platform, their status
is set to PENDING_VERIFICATION
on the database. It might be the case that they had to leave their computer at that moment and were not able to complete the verification process.
To ensure that the user is not lost, it could be a good solution to implement a regular job for sending reminders to unverified users with a Call-to-Action to complete their verification.
1. Define your task
Create a new file in /app/server/jobs.ts
import { Database } from '@/core/database'
import { CronServer } from '@/plugins/cron/server'
import { EmailServer } from '@/plugins/email/server'
CronServer.service.registerJob('0 10 * * *', async () => {
const users = await Database.user.findMany({
where: {
status: 'PENDING_VERIFICATION',
},
})
const urlVerification = '<link_to_verify>'
for (const user of users) {
await EmailServer.service.send({
type: 'authentication-reminder',
name: user.name ?? user.email,
email: user.email,
subject: `You still haven't verified your account!`,
variables: {
url_verification: urlVerification,
},
})
}
})
The first argument of the CronServer.service.registerJob
function is the schedule represented with the Cron Syntax standard.
In this scenario, this script will be sceduled to run every day at 10am.
Note: The script also assumes that you have an email template with the type:
authentication-reminder
which expects aurl_verification
variable.
2. Import the file in your server
Update app/server/index.tsx
to include the following code:
...
import './jobs'
...
This ensures that all jobs defined inside ./jobs.ts
will be registered and scheduled to run at their specified schedules as soon as your app starts/restarts.