说起来也挺奇怪的,Parse Platform本身基于js实现,Node生态里的任务调度实现起来并不麻烦,Parse却选择了不集成,使用第三方提供的任务调度。这里使用node-cron来实现Parse Server中的Job调度。
Parse.Cloud.job("test", async (request) => {
// params: passed in the job call
// headers: from the request that triggered the job
// log: the ParseServer logger passed in the request
// message: a function to update the status message of the job object
const { message } = request
message('done')
})async function callParseJob(parseServerUrl: string, name: string, data?: any) {
console.log(`node-cron: callParseJob ${name}`)
const options: RequestInit = {
method: 'POST',
headers: {
'X-Parse-Application-Id': process.env.APP_ID ?? '',
'X-Parse-Master-Key': process.env.MASTER_KEY ?? ''
}
}
if (data != null) {
options.body = JSON.stringify(data)
}
const res = await fetch(`${parseServerUrl}/jobs/${name}`, options)
console.log(`node-cron: job ${name} finished, ${res.statusText}`)
return await res.json()
}这里选择通过单独的进程来运行调度程序
if (cluster.isPrimary) {
cron.schedule('* * * * *', async () => await callParseJob(process.env.SERVER_URL ?? '', 'test'))
cluster.fork() // 根据cpu个数fork子进程
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' exited')
cluster.fork() //新建一个worker
})
} else {
const app = express()
//...启动Server相关的代码,这里省略
}