This page looks best with JavaScript enabled

Batch Operations in AdonisJS

 ·   ·  ☕ 2 min read

Use Adonis Scheduler to create batch tasks as well as schedule execution of said tasks.

Adonis Scheduler improves your efficiency in writing batch jobs. I am talking about bulk operations that may or may not be suitable for your general purpose service and controllers.

Although scheduler’s purpose seems to be, well, scheduling stuff we can reuse Tasks enabled by scheduler to run bulk operations.

Install Scheduler

First, install scheduler -

1
yarn add adonis-scheduler

Let AdonisJS know that you have added scheduler -

1
2
3
4
5
6
7
8
9
// start/app.js

const providers = ["adonis-scheduler/providers/SchedulerProvider"];

const aliases = {
  Scheduler: "Adonis/Addons/Scheduler"
};

const aceProviders = ["adonis-scheduler/providers/CommandsProvider"];

You are now ready to roll.

Setup your service

Technically you don’t require a service, but it may be a good idea to separate the task schedule logic and the actual operations.

Create app/Services folder if it does not exist.

Create a new file in this folder called DummyLogService.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// DummyLogService.js

"use strict";
const Logger = use("Logger");

class DummyLogService {
  async logThis() {
    console.log("i am log", Date.now());
  }
}
module.exports = new DummyLogService();

Your service is ready to use.

You can create a route and test this service as well.

1
2
3
4
5
6
// routes.js

const DummyLogService = use("App/Services/DummyLogService");
Route.post("/dummy-log", ({ request }) => {
  DummyLogService.logThis();
});

Schedule task

Create a folder app/Tasks if it does not exist.

Create new file in the folder called DummyLogTask.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// DummyLogTask.js

"use strict";
const Task = use("Task");
const DummyLogService = use("App/Services/DummyLogService");

class DummyLogTask extends Task {
  static get schedule() {
    return "* 1 * * * *";
  }

  async handle() {
    try {
      DummyLogService.logThis();
    } catch (e) {
      console.log("Error running task. ", e);
    }
  }
}

module.exports = DummyLogTask;

This task runs every minute and invokes the specified service. The service writes a console.log and exits.

For a full list of scheduling options, refer docs.

Run task

Just run -

1
node ace run:scheduler

This will run all scheduled jobs within the Tasks folder. You will start seeing your beloved console statements soon enough.

You can schedule tasks in production using PM2.

1
pm2 start ./ace -- scheduler:run
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things