3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AdonisJs で adonis-scheduler を使って cron を設定する

Last updated at Posted at 2018-04-04

概要

表題の通り、AdonisJs で adonis-scheduler を使って cron を設定して、タスクを自動で実行する。
AdonisJs のバージョンは 4.1 を使う。

初期設定

adonis-scheduler をインストールする。

$ npm install --save adonis-scheduler

start/app.js で各種設定をする。

start/app.js
const providers = [
  ...
  'adonis-scheduler/providers/SchedulerProvider'
]

const aliases = {
  ...
  Scheduler: 'Adonis/Addons/Scheduler'
}

const aceProviders = [
  ...
  'adonis-scheduler/providers/CommandsProvider'
]

タスクをつくる

まずは、実行するタスクをつくる。
ここでは、試しに Example というタスクをつくって、実行してみる。

$ adonis make:task Example

もしくは

$ node ace make:task Example

を叩くと、app/TasksExample.js というファイルが生成される。

app/Tasks/Example.js
'use strict'

const Task = use('Task')

class Example extends Task {
  static get schedule () {
    return '0 */1 * * * *'
  }

  async handle () {
    this.info('Task Example handle')
  }
}

module.exports = Example

あとは、schedule に実行条件、handle に実行内容を書けば良い。
実行条件は、node-schedule と同じ記法で書くことができる。

実行する

ここまでできれば、あとは実行すれば良いだけである。

$ adonis run:scheduler

もしくは

$ node ace run:scheduler

で起動するので、package.jsonscripts を以下のように変えてあげると良い。

package.json
{
  ...
  "scripts": {
    "start": "node server.js & node ace run:scheduler"
  }
}

実行して、ターミナルにこのようなログが流れればオッケー!(試しにやるときは、実行条件を毎秒とかにすると良い)

2018-04-04T05:39:40.007Z - info: { task: 'example' } 'Task Example handle'

おまけ

個人的に package.jsonscripts をゴチャゴチャさせたくないし、普通にサーバーが立ち上がるときに scheduler も立ち上がってくれていいよとなった。

そのような場合は、以下のようなファイルをつくって

start/schedule.js
'use strict'

const Scheduler = use('Scheduler')
Scheduler.run()

server.js で呼び出すとうまく動く。

server.js
'use strict'

const { Ignitor } = require('@adonisjs/ignitor')

new Ignitor(require('@adonisjs/fold'))
  .appRoot(__dirname)
  .preLoad('start/scheduler') // ここを足した
  .fireHttpServer()
  .catch(console.error)
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?