0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Node.js × Cron】TypeScriptで複数タスクを管理する方法

Posted at

はじめに

定期的に処理を実行したい場合、Node.jsではnode-cronを使うことで簡単に実現できます。本記事では、TypeScriptでタスクスケジューラを実装し、複数の処理を定期実行する方法を紹介します。

node-cronとは?

node-cronは、UNIX系OSで使われる「cron」の書式に従って、Node.jsでスケジュールタスクを登録・実行するライブラリです。たとえば "0 * * * *" は「毎時0分」にタスクを実行することを意味します。

Cron式の構成

* * * * * *
│ │ │ │ │ │
│ │ │ │ │ └── 曜日 (0 - 7) (0または7は日曜日)
│ │ │ │ └──── 月 (1 - 12)
│ │ │ └────── 日 (1 - 31)
│ │ └──────── 時 (0 - 23)
│ └────────── 分 (0 - 59)
└──────────── 秒 (省略可)

例:0 * * * * → 毎時0分に実行される

クラスの実装

TaskSchedulerクラスを使って、複数のCronタスクを登録・停止・一括停止できるようにしています。

1. 型定義

TaskScheduler.ts
interface TaskConfig {
  name: string;
  cronExpression: string;
  command: () => Promise<void>;
}

interface ScheduledTasks {
  [taskName: string]: cron.ScheduledTask;
}
  • TaskConfig: 各タスクの構成情報(名前、cron式、実行関数)を定義
  • ScheduledTasks: タスク名とnode-cronScheduledTaskオブジェクトの対応表

2. TaskSchedulerクラスの概要

TaskScheduler.ts
class TaskScheduler {
  private scheduledTasks: ScheduledTasks = {};
  private taskConfig: TaskConfig[] = [
    {
      name: "task1",
      cronExpression: "0 * * * *",
      command: async () => {
        await Task1.main();
      }
    },
    ...
  ];
  • scheduledTasks: 実行中のスケジュールタスクを管理
  • taskConfig: 登録したいタスクのリスト。必要に応じて外部ファイルやDBにしてもOK

3. タスクの登録処理(scheduleTask

TaskScheduler.ts
private scheduleTask(taskConfig: TaskConfig): void {
  const { name, cronExpression, command } = taskConfig;

  if (this.scheduledTasks[name]) {
    Logger.warning(`Task "${name}" already scheduled. Stopping existing task.`);
    this.scheduledTasks[name]!.stop();
  }

  const job = cron.schedule(cronExpression, async () => {
    try {
      await command();
    } catch (error) {
      Logger.error(`Error running ${name}: ${error}`);
    }
  });

  this.scheduledTasks[name] = job;
  Logger.info(`Task "${name}" scheduled with cron "${cronExpression}"`);
}
  • 既に同名タスクが存在すれば、先に止める(上書き防止)
  • cron.scheduleで新しいジョブを作成
  • 非同期関数にも対応(async/await

4. タスクの停止処理

TaskScheduler.ts
public stopTask(taskName: string): void {
  if (this.scheduledTasks[taskName]) {
    this.scheduledTasks[taskName]!.stop();
    delete this.scheduledTasks[taskName];
    Logger.info(`Task "${taskName}" stopped.`);
  } else {
    Logger.warning(`Task "${taskName}" not found.`);
  }
}

指定されたタスクを停止し、一覧からも削除します。

5. 全タスクの停止

TaskScheduler.ts
public stopAllTasks(): void {
  Logger.task("Stopping all scheduled tasks...");
  for (const taskName in this.scheduledTasks) {
    this.scheduledTasks[taskName]!.stop();
    Logger.info(`Task "${taskName}" not stopped.`);
  }

  this.scheduledTasks = {};
  Logger.success("All scheduled tasks stopped.");
}
  • 全タスクをループで止める
  • scheduledTasksを初期化して完全リセット

クラスの使い方(例)

TaskScheduler.ts
import TaskScheduler from './TaskScheduler';

TaskScheduler.start(); // 必要に応じて startAllTasks を作成してもOK

おわりに

この記事では、TypeScriptでnode-cronを使って複数のタスクを効率よく管理するスケジューラの実装方法を紹介しました。

  • タスクの再スケジュール
  • エラー処理の取り扱い
  • 管理用のインターフェース設計

など、実務でも活かせる構成になっていると思います。参考になれば幸いです!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?