Skip to content

Instantly share code, notes, and snippets.

@Nabihabou
Last active July 28, 2023 01:22
Show Gist options
  • Save Nabihabou/1e41ad20f3678877fb26826922f6f07e to your computer and use it in GitHub Desktop.
Save Nabihabou/1e41ad20f3678877fb26826922f6f07e to your computer and use it in GitHub Desktop.
Vite plugin for cron jobs
/* Setup */
import { cronPlugin } from './src/lib/CronPlugin';
export default defineConfig({
plugins: [
cronPlugin(jobs)
]
});
/* Plugin */
import type { Plugin } from 'vite';
import { CronJob } from 'cron';
export interface CronPluginOptions {
name: string;
cronSchedule: string;
onTick: () => void;
}
export function cronPlugin(options: CronPluginOptions[]): Plugin {
let jobs: CronJob[] = [];
for (const job in options) {
try {
const cronJob = new CronJob(options[job].cronSchedule, options[job].onTick);
console.log(`✅ Registered job: ${options[job].name}`);
jobs.push(cronJob)
} catch (err) {
console.log(`❌ Failed to create job: ${options[job].name}\n${err}`);
}
}
return {
name: 'cron-vite-plugin',
configureServer() {
for (const job in jobs) {
jobs[job].addCallback(() => {
console.log(`🕒 Executing job: ${options[job].name}`);
});
jobs[job].start();
}
},
closeBundle() {
for (const job in jobs) {
jobs[job].stop();
}
},
};
}
/* Jobs */
import type { CronPluginOptions } from "./src/lib/CronPlugin";
const jobs = [
{
name: 'Cron01',
cronSchedule: '*/5 * * * * *', // every 5 seconds
onTick: async () => {
try {
await fetch('http://localhost:5173/api/test')
} catch (err) {
console.log(err)
}
}
},
{
name: 'Cron02',
cronSchedule: '*/20 * * * * *', // every 20 seconds
onTick: async () => {
try {
await fetch('http://localhost:5173/api/test')
} catch (err) {
console.log(err)
}
}
},
] satisfies CronPluginOptions[]
export default jobs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment