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
// src/server/jobs.ts
import { Database } from '@/core/database'
import { CronService } from './libraries/cron'
import { EmailService } from './libraries/email'
import { EmailType } from './libraries/email/internal/email.type'
CronService.registerJob('0 10 * * *', async () => {
const users = await Database.getUnprotected().user.findMany({
where: {
status: 'PENDING_VERIFICATION',
},
})
const urlVerification = '<link_to_verify>'
for (const user of users) {
await EmailService.send({
type: EmailType.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 CronService.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
src/server/index.tsx
...
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.