scheduler.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const PgBoss = require('pg-boss')
  2. const { DynamicThreadPool } = require('poolifier')
  3. const os = require('node:os')
  4. /* global WIKI */
  5. module.exports = {
  6. pool: null,
  7. scheduler: null,
  8. async init () {
  9. WIKI.logger.info('Initializing Scheduler...')
  10. this.scheduler = new PgBoss({
  11. db: {
  12. close: () => Promise.resolve('ok'),
  13. executeSql: async (text, values) => {
  14. try {
  15. const resource = await WIKI.models.knex.client.pool.acquire().promise
  16. const res = await resource.query(text, values)
  17. WIKI.models.knex.client.pool.release(resource)
  18. return res
  19. } catch (err) {
  20. WIKI.logger.error('Failed to acquire DB connection during scheduler query execution.')
  21. WIKI.logger.error(err)
  22. }
  23. }
  24. },
  25. // ...WIKI.models.knex.client.connectionSettings,
  26. application_name: 'Wiki.js Scheduler',
  27. schema: WIKI.config.db.schemas.scheduler,
  28. uuid: 'v4'
  29. })
  30. const maxWorkers = WIKI.config.workers === 'auto' ? os.cpus().length : WIKI.config.workers
  31. WIKI.logger.info(`Initializing Worker Pool (Max ${maxWorkers})...`)
  32. this.pool = new DynamicThreadPool(1, maxWorkers, './server/worker.js', {
  33. errorHandler: (err) => WIKI.logger.warn(err),
  34. exitHandler: () => WIKI.logger.debug('A worker has gone offline.'),
  35. onlineHandler: () => WIKI.logger.debug('New worker is online.')
  36. })
  37. return this
  38. },
  39. async start () {
  40. WIKI.logger.info('Starting Scheduler...')
  41. await this.scheduler.start()
  42. this.scheduler.work('*', async job => {
  43. return this.pool.execute({
  44. id: job.id,
  45. name: job.name,
  46. data: job.data
  47. })
  48. })
  49. WIKI.logger.info('Scheduler: [ STARTED ]')
  50. },
  51. async stop () {
  52. WIKI.logger.info('Stopping Scheduler...')
  53. await this.scheduler.stop()
  54. await this.pool.destroy()
  55. WIKI.logger.info('Scheduler: [ STOPPED ]')
  56. }
  57. }