Batch Operations in AdonisJS

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 -

yarn add adonis-scheduler

Let AdonisJS know that you have added scheduler -

// 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.

// 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.

// 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.

// 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 -

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.

pm2 start ./ace -- scheduler:run
comments powered by Disqus