{"id":21007644,"url":"https://github.com/jongolden/agenda-nest","last_synced_at":"2025-05-15T02:31:34.622Z","repository":{"id":36982709,"uuid":"504883176","full_name":"jongolden/agenda-nest","owner":"jongolden","description":"A lightweight job scheduler for NestJS","archived":false,"fork":false,"pushed_at":"2024-09-04T02:31:09.000Z","size":6383,"stargazers_count":20,"open_issues_count":6,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-15T04:36:30.146Z","etag":null,"topics":["agendajs","nestjs","queue","schedule"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jongolden.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-06-18T15:39:59.000Z","updated_at":"2024-10-30T03:51:17.000Z","dependencies_parsed_at":"2024-10-20T20:08:04.696Z","dependency_job_id":null,"html_url":"https://github.com/jongolden/agenda-nest","commit_stats":{"total_commits":44,"total_committers":4,"mean_commits":11.0,"dds":0.5227272727272727,"last_synced_commit":"1d110ae19fd50168613247e5c6f3a4404f8bee7c"},"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jongolden%2Fagenda-nest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jongolden%2Fagenda-nest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jongolden%2Fagenda-nest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jongolden%2Fagenda-nest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jongolden","download_url":"https://codeload.github.com/jongolden/agenda-nest/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225198132,"owners_count":17436833,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agendajs","nestjs","queue","schedule"],"created_at":"2024-11-19T09:09:28.188Z","updated_at":"2024-11-19T09:09:28.731Z","avatar_url":"https://github.com/jongolden.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Agenda Nest\n\n\u003ca href=\"https://www.npmjs.com/package/agenda-nest\" target=\"_blank\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/agenda-nest.svg\" alt=\"NPM Version\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://www.npmjs.com/package/agenda-nest\" target=\"_blank\"\u003e\u003cimg src=\"https://img.shields.io/npm/l/agenda-nest.svg\" alt=\"Package License\" /\u003e\u003c/a\u003e\n\u003c/p\u003e\n\nA lightweight job scheduler for NestJS\n\n## Table of Contents\n- [Background](#background)\n- [Install](#install)\n- [Configure Agenda](#configure-agenda)\n- [Job processors](#job-processors)\n- [Job schedulers](#job-schedulers)\n- [Event listeners](#event-listeners)\n- [Manually working with a queue](#manually-working-with-a-queue)\n- [License](#license)\n\n## Background\n\nAgenda Nest provides a NestJS module wrapper for [Agenda](https://github.com/agenda/agenda), a lightweight job scheduling library.  Heavily inspired by Nest's own Bull implementation, [@nestjs/bull](https://github.com/nestjs/bull), Agenda Nest provides a fully-featured implementation, complete with decorators for defining your jobs, processors and queue event listeners.  You may optionally, make use of Agenda Nest's Express controller to interface with your queues through HTTP.\n\n### Dependencies\n\nAgenda uses MongoDB to persist job data, so you'll need to have Mongo (or mongoose) installed on your system.\n\n## Install\n\n```bash\nnpm install agenda-nest\n```\n\n## Configure Agenda\n\nAs Agenda Nest is a wrapper for Agenda, it is configurable with same properties as the Agenda instance. Refer to [AgendaConfig](https://github.com/agenda/agenda/blob/master/lib/agenda/index.ts#L39) for the complete configuration type.\n\n### Synchronously\n\n```ts\nimport { Module } from '@nestjs/common'\nimport { AgendaModule } from 'agenda-nest';\n\n@Module({\n  imports: [\n    AgendaModule.forRoot({\n      processEvery: '3 minutes',\n      db: {\n        addresss: 'mongodb://localhost:27017',\n      },\n    }),\n  ],\n  providers: [Jobs],\n})\nexport class AppModule {}\n```\n\n### Asynchronously\n\n```ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { AgendaModule } from 'agenda-nest';\nimport configuration from './configuration';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [configuration],\n    }),\n    AgendaModule.forRootAsync({\n      useFactory: (config: ConfigService) =\u003e ({\n        processEvery: config.get('queues.processInterval'),\n        db: {\n          address: config.get('database.connectionString'),\n        },\n      }),\n      inject: [ConfigService],\n    })\n  ],\n  providers: [Jobs],\n})\nexport class AppModule {}\n```\n\n## Configure queues\n\nAgenda Nest can manage multiple queues within your application.  To configure a new queue use `AgendaModule.registerQueue(queueName: string, config: AgendaConfig)`.  Queues will inherit the configuration provided to `Agenda.forRoot`, merging and overriding properties provided to the queue.\n\n### Synchronously\n\n```ts\nimport { Module } from '@nestjs/common';\nimport { AgendaModule } from 'agenda-nest';\n\n@Module({\n  imports: [\n    AgendaModule.registerQueue('notifications', {\n      processEvery: '5 minutes',\n      autoStart: false, // default: true\n      collection: 'notificationsqueue', // default: notifications-queue (`${queueName}-queue`)\n    }),\n  ],\n})\nexport class NotificationsModule {}\n```\n\n### Asynchronously\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { AgendaModule } from 'agenda-nest';\n\n@Module({\n  imports: [\n    AgendaModule.registerQueueAsync('notifications', {\n      useFactory: (config: ConfigService) =\u003e ({\n        processEvery: config.get('queues.notifications.processInterval'),\n        autoStart: config.get('queues.notifications.autoStart'),\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n})\nexport class NotificationsModule {}\n```\n\n## Job processors\n\nJob processors are methods defined on a class declared with the `@Queue(name: string)` decorator.  The queue name will be used to create the MongoDB collection, formatted as `\"{queue Name}-queue\"`, for each queue. You can also specify your own collection name.\n\n```js\nimport { Queue } from 'agenda-nest';\n\n// will use a \"notifications-queue\" collection\n@Queue('notifications')\nexport class NotificationsQueue {}\n\n// with custom collection name\n@Queue('notifications', { collection: 'notificationsqueue' })\nexport class NotificationsQueue {}\n```\n\nTo **define**, but not schedule, a job on the queue, use the `@Define()` decorator as shown below.  To define a scheduled job, see [Job schedulers](#job-schedulers).\n\n```js\nimport { Define, Queue, Job } from 'agenda-nest';\n\n@Queue('notifications')\nexport class NotificationsQueue {\n  @Define()\n  sendNotification(job: Job) {}\n}\n```\n\n## Job schedulers\n\nTo define and schedule a job on the queue, use one of the `@Every()`, `@Schedule()`, or `@Now()` decorators. See Agenda's [Creating Jobs](https://github.com/agenda/agenda#creating-jobs) documentation for an explanation on the behavior of each.\n\n### `@Every(nameOrOptions: string | JobOptions)`\n\nDefines a job to run at the given interval\n\n```js\nimport { Every, Queue, Job } from 'agenda-nest';\n\n@Queue('notifications')\nexport class NotificationsQueue {\n  @Every({ name: 'send notifications', interval: '15 minutes' })\n  async sendNotifications(job: Job) {\n    const users = await User.doSomethingReallyIntensive();\n    sendNotification(users, \"Welcome!\");\n  }\n}\n\n@Queue('reports')\nexport class ReportsQueue {\n  @Every('15 minutes')\n  async printAnalyticsReport(job: Job) {\n    const users = await User.doSomethingReallyIntensive();\n    processUserData(users);\n  }\n}\n\n```\n\n### `@Schedule(nameOrOptions: string | JobOptions)`\n\nSchedules a job to run once at the given time.\n\n```js\nimport { Schedule, Queue, Job } from 'agenda-nest';\n\n@Queue('notifications')\nexport class NotificationsQueue {\n  @Scheduler({ name: 'send notifications', when: 'tomorrow at noon' })\n  async sendNotifications(job: Job) {\n    const users = await User.doSomethingReallyIntensive();\n    sendNotification(users, \"Welcome!\");\n  }\n}\n\n@Queue('reports')\nexport class ReportsQueue {\n  @Schedule('tomorrow at noon')\n  async printAnalyticsReport(job: Job) {\n    const users = await User.doSomethingReallyIntensive();\n    processUserData(users);\n  }\n}\n\n```\n\n### `@Now(name?: string)`\n\nSchedules a job to run once immediately.\n\n```js\nimport { Now, Queue, Job } from 'agenda-nest';\n\n@Queue('dance')\nexport class DanceQueue {\n  @Now()\n  async doTheHokeyPokey(job: Job) {\n    hokeyPokey();\n  }\n\n  @Now('do the cha-cha')\n  async doTheChaCha(job: Job) {\n    chaCha();\n  }\n}\n\n```\n\n## Event Listeners\n\nAgenda generates a set of useful events when queue and/or job state changes occur. Agenda NestJS provides a set of decorators that allow subscribing to a core set of standard events.\n\nEvent listeners must be declared within an injectable class (i.e., within a class decorated with the @Queue() decorator). To listen for an event, use one of the decorators in the table below to declare a handler for the event. For example, to listen to the event emitted when a job enters the active state in the audio queue, use the following construct:\n\n```js\nimport { OnQueueReady } from 'agenda-nest';\nimport { Job } from 'agenda';\n\n@Queue()\nexport class JobsQueue {\n  @OnQueueReady()\n  onReady() {\n    console.log('Jobs queue is ready to run our jobs');\n  }\n  ...\n```\n\n### Agenda Events\n\nAn instance of an agenda will emit the queue events listed below. Use the corresponding method decorator to listen for and handle each event.\n\n| Event   | Listener          |                                                                                |\n|:--------|:------------------|:-------------------------------------------------------------------------------|\n| `ready` | `@OnQueueReady()` | called when Agenda mongo connection is successfully opened and indices created |\n| `error` | `@OnQueueError()` | called when Agenda mongo connection process has thrown an error                |\n\n### Job Queue Events\n\nAn instance of an agenda will emit the job events listed below. Use the corresponding method decorator to listen for and handle each event.\n\n| Event                             | Listener                        |                                                                   |\n|:----------------------------------|:--------------------------------|:------------------------------------------------------------------|\n| `start` or `start:job name`       | `@OnJobStart(name?: string)`    | called just before a job starts                                   |\n| `complete` or `complete:job name` | `@OnJobComplete(name?: string)` | called when a job finishes, regardless of if it succeeds or fails |\n| `success` or `success:job name`   | `@OnJobSuccess(name?: string)`  | called when a job finishes successfully                           |\n| `fail` or `fail:job name`         | `@OnJobFail(name?: string)`     | called when a job throws an error                                 |\n\n## Manually working with a queue\n\nYou can access any registered queue using the `@InjectQueue(queueName)` decorator, which will inject the instance of `Agenda` for the given queue name. See Agenda's [documentation](https://github.com/agenda/agenda#table-of-contents) for the available API.\n\n```js\n@Injectable()\nexport class NotificationsService {\n  constructor(@InjectQueue('notificiations') private queue: Agenda) {}\n\n  async scheduleNotification(sendAt: string) {\n    await this.queue.schedule('tomorrow at noon', 'sendNotification', {\n      to: 'user@example.com',\n    });\n  }\n}\n```\n\n## License\n\nAgenda Nest is [MIT licensed](https://github.com/jongolden/agenda-nest/blob/main/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjongolden%2Fagenda-nest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjongolden%2Fagenda-nest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjongolden%2Fagenda-nest/lists"}