{"id":13406657,"url":"https://github.com/agenda/agenda","last_synced_at":"2026-02-26T01:26:35.709Z","repository":{"id":11476098,"uuid":"13945143","full_name":"agenda/agenda","owner":"agenda","description":"Lightweight job scheduling for Node.js","archived":false,"fork":false,"pushed_at":"2024-09-05T22:41:22.000Z","size":4424,"stargazers_count":9581,"open_issues_count":355,"forks_count":830,"subscribers_count":120,"default_branch":"master","last_synced_at":"2025-11-05T23:18:32.691Z","etag":null,"topics":["automated","cron","cronjob","crontab","frequency","interval","job","job-processor","job-scheduler","mongodb","nodejs","queue","recurring","runner","schedule","scheduler","task"],"latest_commit_sha":null,"homepage":"http://agendajs.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/agenda.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","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":"2013-10-29T02:58:41.000Z","updated_at":"2025-11-04T23:53:47.000Z","dependencies_parsed_at":"2024-06-18T10:59:28.445Z","dependency_job_id":"9f28608b-3553-4d0e-b6c0-3ff71017e2bf","html_url":"https://github.com/agenda/agenda","commit_stats":{"total_commits":944,"total_committers":143,"mean_commits":6.601398601398602,"dds":0.823093220338983,"last_synced_commit":"41a2b3793400073f564c37f7d2d0ec2d7e237bf2"},"previous_names":["rschmukler/agenda"],"tags_count":87,"template":false,"template_full_name":null,"purl":"pkg:github/agenda/agenda","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agenda%2Fagenda","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agenda%2Fagenda/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agenda%2Fagenda/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agenda%2Fagenda/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/agenda","download_url":"https://codeload.github.com/agenda/agenda/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agenda%2Fagenda/sbom","scorecard":{"id":170367,"data":{"date":"2025-08-11","repo":{"name":"github.com/agenda/agenda","commit":"41a2b3793400073f564c37f7d2d0ec2d7e237bf2"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3.4,"checks":[{"name":"Code-Review","score":2,"reason":"Found 5/22 approved changesets -- score normalized to 2","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28","Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29","Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1","Warn: no topLevel permission defined: .github/workflows/docs.yml:1","Warn: no topLevel permission defined: .github/workflows/test.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/codeql-analysis.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/codeql-analysis.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:59: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/codeql-analysis.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:72: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/codeql-analysis.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/docs.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/docs.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/docs.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/docs.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/docs.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/docs.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/test.yml/master?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/test.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/agenda/agenda/test.yml/master?enable=pin","Warn: npmCommand not pinned by hash: .github/workflows/docs.yml:27","Warn: npmCommand not pinned by hash: .github/workflows/docs.yml:30","Warn: npmCommand not pinned by hash: .github/workflows/test.yml:38","Warn: npmCommand not pinned by hash: .github/workflows/test.yml:41","Info:   0 out of  10 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   1 third-party GitHubAction dependencies pinned","Info:   0 out of   4 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE.md:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":7,"reason":"SAST tool detected but not run on all commits","details":["Info: SAST configuration detected: CodeQL","Warn: 0 commits out of 14 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"18 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-968p-4wvh-cqc8","Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-4q6p-r6v2-jvc5","Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22","Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp","Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h","Warn: Project is vulnerable to: GHSA-3xq5-wjfh-ppjc","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-vxvm-qww3-2fh7","Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55","Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-76p7-773f-r4q5","Warn: Project is vulnerable to: GHSA-52f5-9888-hmc6","Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-16T16:16:21.339Z","repository_id":11476098,"created_at":"2025-08-16T16:16:21.339Z","updated_at":"2025-08-16T16:16:21.339Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27772609,"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","status":"online","status_checked_at":"2025-12-16T02:00:10.477Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["automated","cron","cronjob","crontab","frequency","interval","job","job-processor","job-scheduler","mongodb","nodejs","queue","recurring","runner","schedule","scheduler","task"],"created_at":"2024-07-30T19:02:35.829Z","updated_at":"2025-12-16T22:55:56.240Z","avatar_url":"https://github.com/agenda.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","Packages","Repository","JavaScript","🔧 Utilities \u0026 Miscellaneous","Node.js","HTML","Job Scheduling and Queues","nodejs","Uncategorized","mongodb","包"],"sub_categories":["Job queues","Job Scheduling","Database","React Components","Uncategorized","工作队列"],"readme":"# Agenda\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://cdn.jsdelivr.net/gh/agenda/agenda@master/agenda.svg\" alt=\"Agenda\" width=\"100\" height=\"100\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  A light-weight job scheduling library for Node.js\n\u003c/p\u003e\n\nThis was originally a fork of agenda.js,\nit differs from the original version in following points:\n\n- Complete rewrite in Typescript (fully typed!)\n- mongodb4 driver (supports mongodb 5.x)\n- Supports mongoDB sharding by name\n- touch() can have an optional progress parameter (0-100)\n- Bugfixes and improvements for locking \u0026 job processing (concurrency, lockLimit,..)\n- Breaking change: define() config paramter moved from 2nd position to 3rd\n- getRunningStats()\n- automatically waits for agenda to be connected before calling any database operations\n- uses a database abstraction layer behind the scene\n- does not create a database index by default, you can set `ensureIndex: true` when initializing Agenda\n  or run manually:\n\n```\ndb.agendaJobs.ensureIndex({\n    \"name\" : 1,\n    \"nextRunAt\" : 1,\n    \"priority\" : -1,\n    \"lockedAt\" : 1,\n    \"disabled\" : 1\n}, \"findAndLockNextJobIndex\")\n```\n\n# Agenda offers\n\n- Minimal overhead. Agenda aims to keep its code base small.\n- Mongo backed persistence layer.\n- Promises based API.\n- Scheduling with configurable priority, concurrency, repeating and persistence of job results.\n- Scheduling via cron or human readable syntax.\n- Event backed job queue that you can hook into.\n- [Agenda-rest](https://github.com/agenda/agenda-rest): optional standalone REST API.\n- [Inversify-agenda](https://github.com/lautarobock/inversify-agenda) - Some utilities for the development of agenda workers with Inversify.\n- [Agendash](https://github.com/agenda/agendash): optional standalone web-interface.\n\n### Feature Comparison\n\nSince there are a few job queue solutions, here a table comparing them to help you use the one that\nbetter suits your needs.\n\n| Feature                    |      Bull       |   Bee    | Agenda |\n| :------------------------- | :-------------: | :------: | :----: |\n| Backend                    |      redis      |  redis   | mongo  |\n| Priorities                 |        ✓        |          |   ✓    |\n| Concurrency                |        ✓        |    ✓     |   ✓    |\n| Delayed jobs               |        ✓        |          |   ✓    |\n| Global events              |        ✓        |          |   ✓    |\n| Rate Limiter               |        ✓        |          |        |\n| Pause/Resume               |        ✓        |          |   ✓    |\n| Sandboxed worker           |        ✓        |          |   ✓    |\n| Repeatable jobs            |        ✓        |          |   ✓    |\n| Atomic ops                 |        ✓        |    ✓     |   ~    |\n| Persistence                |        ✓        |    ✓     |   ✓    |\n| UI                         |        ✓        |          |   ✓    |\n| REST API                   |                 |          |   ✓    |\n| Central (Scalable) Queue   |                 |          |   ✓    |\n| Supports long running jobs |                 |          |   ✓    |\n| Optimized for              | Jobs / Messages | Messages |  Jobs  |\n\n_Kudos for making the comparison chart goes to [Bull](https://www.npmjs.com/package/bull#feature-comparison) maintainers._\n\n# Installation\n\nInstall via NPM\n\n    npm install @hokify/agenda\n\nYou will also need a working [Mongo](https://www.mongodb.com/) database (v4+) to point it to.\n\n# Example Usage\n\n```js\nconst mongoConnectionString = 'mongodb://127.0.0.1/agenda';\n\nconst agenda = new Agenda({ db: { address: mongoConnectionString } });\n\n// Or override the default collection name:\n// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName'}});\n\n// or pass additional connection options:\n// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName', options: {ssl: true}}});\n\n// or pass in an existing mongodb-native MongoClient instance\n// const agenda = new Agenda({mongo: myMongoClient});\n\nagenda.define('delete old users', async job =\u003e {\n\tawait User.remove({ lastLogIn: { $lt: twoDaysAgo } });\n});\n\n(async function () {\n\t// IIFE to give access to async/await\n\tawait agenda.start();\n\n\tawait agenda.every('3 minutes', 'delete old users');\n\n\t// Alternatively, you could also do:\n\tawait agenda.every('*/3 * * * *', 'delete old users');\n})();\n```\n\n```js\nagenda.define(\n\t'send email report',\n\tasync job =\u003e {\n\t\tconst { to } = job.attrs.data;\n\t\tawait emailClient.send({\n\t\t\tto,\n\t\t\tfrom: 'example@example.com',\n\t\t\tsubject: 'Email Report',\n\t\t\tbody: '...'\n\t\t});\n\t},\n\t{ priority: 'high', concurrency: 10 }\n);\n\n(async function () {\n\tawait agenda.start();\n\tawait agenda.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' });\n})();\n```\n\n```js\n(async function () {\n\tconst weeklyReport = agenda.create('send email report', { to: 'example@example.com' });\n\tawait agenda.start();\n\tawait weeklyReport.repeatEvery('1 week').save();\n})();\n```\n\n# Full documentation\n\nSee also https://hokify.github.io/agenda/\n\nAgenda's basic control structure is an instance of an agenda. Agenda's are\nmapped to a database collection and load the jobs from within.\n\n## Table of Contents\n\n- [Configuring an agenda](#configuring-an-agenda)\n- [Agenda Events](#agenda-events)\n- [Defining job processors](#defining-job-processors)\n- [Creating jobs](#creating-jobs)\n- [Managing jobs](#managing-jobs)\n- [Starting the job processor](#starting-the-job-processor)\n- [Multiple job processors](#multiple-job-processors)\n- [Manually working with jobs](#manually-working-with-a-job)\n- [Job Queue Events](#job-queue-events)\n- [Frequently asked questions](#frequently-asked-questions)\n- [Example Project structure](#example-project-structure)\n- [Known Issues](#known-issues)\n- [Debugging Issues](#debugging-issues)\n- [Acknowledgements](#acknowledgements)\n\n## Configuring an agenda\n\nAll configuration methods are chainable, meaning you can do something like:\n\n```js\nconst agenda = new Agenda();\nagenda\n  .database(...)\n  .processEvery('3 minutes')\n  ...;\n```\n\nPossible agenda config options:\n\n```ts\n{\n\tname: string;\n\tdefaultConcurrency: number;\n\tprocessEvery: number;\n\tmaxConcurrency: number;\n\tdefaultLockLimit: number;\n\tlockLimit: number;\n\tdefaultLockLifetime: number;\n\tensureIndex: boolean;\n\tsort: SortOptionObject\u003cIJobParameters\u003e;\n\tdb: {\n\t\tcollection: string;\n\t\taddress: string;\n\t\toptions: MongoClientOptions;\n\t}\n\tmongo: Db;\n}\n```\n\nAgenda uses [Human Interval](http://github.com/rschmukler/human-interval) for specifying the intervals. It supports the following units:\n\n`seconds`, `minutes`, `hours`, `days`,`weeks`, `months` -- assumes 30 days, `years` -- assumes 365 days\n\nMore sophisticated examples\n\n```js\nagenda.processEvery('one minute');\nagenda.processEvery('1.5 minutes');\nagenda.processEvery('3 days and 4 hours');\nagenda.processEvery('3 days, 4 hours and 36 seconds');\n```\n\n### database(url, [collectionName], [MongoClientOptions])\n\nSpecifies the database at the `url` specified. If no collection name is given,\n`agendaJobs` is used.\n\nBy default `useNewUrlParser` and `useUnifiedTopology` is set to `true`,\n\n```js\nagenda.database('localhost:27017/agenda-test', 'agendaJobs');\n```\n\nYou can also specify it during instantiation.\n\n```js\nconst agenda = new Agenda({\n\tdb: { address: 'localhost:27017/agenda-test', collection: 'agendaJobs' }\n});\n```\n\nAgenda will emit a `ready` event (see [Agenda Events](#agenda-events)) when properly connected to the database.\nIt is safe to call `agenda.start()` without waiting for this event, as this is handled internally.\nIf you're using the `db` options, or call `database`, then you may still need to listen for `ready` before saving jobs.\n\n### mongo(dbInstance, [collectionName])\n\nUse an existing mongodb-native MongoClient/Db instance. This can help consolidate connections to a\ndatabase. You can instead use `.database` to have agenda handle connecting for you.\n\nYou can also specify it during instantiation:\n\n```js\nconst agenda = new Agenda({ mongo: mongoClientInstance.db('agenda-test') });\n```\n\nNote that MongoClient.connect() returns a mongoClientInstance since [node-mongodb-native 3.0.0](https://github.com/mongodb/node-mongodb-native/blob/master/CHANGES_3.0.0.md), while it used to return a dbInstance that could then be directly passed to agenda.\n\n### name(name)\n\nSets the `lastModifiedBy` field to `name` in the jobs collection.\nUseful if you have multiple job processors (agendas) and want to see which\njob queue last ran the job.\n\n```js\nagenda.name(os.hostname + '-' + process.pid);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ name: 'test queue' });\n```\n\n### processEvery(interval)\n\nTakes a string `interval` which can be either a traditional javascript number,\nor a string such as `3 minutes`\n\nSpecifies the frequency at which agenda will query the database looking for jobs\nthat need to be processed. Agenda internally uses `setTimeout` to guarantee that\njobs run at (close to ~3ms) the right time.\n\nDecreasing the frequency will result in fewer database queries, but more jobs\nbeing stored in memory.\n\nAlso worth noting is that if the job queue is shutdown, any jobs stored in memory\nthat haven't run will still be locked, meaning that you may have to wait for the\nlock to expire. By default it is `'5 seconds'`.\n\n```js\nagenda.processEvery('1 minute');\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ processEvery: '30 seconds' });\n```\n\n### maxConcurrency(number)\n\nTakes a `number` which specifies the max number of jobs that can be running at\nany given moment. By default it is `20`.\n\n```js\nagenda.maxConcurrency(20);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ maxConcurrency: 20 });\n```\n\n### defaultConcurrency(number)\n\nTakes a `number` which specifies the default number of a specific job that can be running at\nany given moment. By default it is `5`.\n\n```js\nagenda.defaultConcurrency(5);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ defaultConcurrency: 5 });\n```\n\n### lockLimit(number)\n\nTakes a `number` which specifies the max number jobs that can be locked at any given moment. By default it is `0` for no max.\n\n```js\nagenda.lockLimit(0);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ lockLimit: 0 });\n```\n\n### defaultLockLimit(number)\n\nTakes a `number` which specifies the default number of a specific job that can be locked at any given moment. By default it is `0` for no max.\n\n```js\nagenda.defaultLockLimit(0);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ defaultLockLimit: 0 });\n```\n\n### defaultLockLifetime(number)\n\nTakes a `number` which specifies the default lock lifetime in milliseconds. By\ndefault it is 10 minutes. This can be overridden by specifying the\n`lockLifetime` option to a defined job.\n\nA job will unlock if it is finished (ie. the returned Promise resolves/rejects\nor `done` is specified in the params and `done()` is called) before the\n`lockLifetime`. The lock is useful if the job crashes or times out.\n\n```js\nagenda.defaultLockLifetime(10000);\n```\n\nYou can also specify it during instantiation\n\n```js\nconst agenda = new Agenda({ defaultLockLifetime: 10000 });\n```\n\n### sort(query)\n\nTakes a `query` which specifies the sort query to be used for finding and locking the next job.\n\nBy default it is `{ nextRunAt: 1, priority: -1 }`, which obeys a first in first out approach, with respect to priority.\n\n### disableAutoIndex(boolean)\n\nOptional. Disables the automatic creation of the default index on the jobs table.\nBy default, Agenda creates an index to optimize its queries against Mongo while processing jobs.\n\nThis is useful if you want to use your own index in specific use-cases.\n\n## Agenda Events\n\nAn instance of an agenda will emit the following events:\n\n- `ready` - called when Agenda mongo connection is successfully opened and indices created.\n  If you're passing agenda an existing connection, you shouldn't need to listen for this, as `agenda.start()` will not resolve until indices have been created.\n  If you're using the `db` options, or call `database`, then you may still need to listen for the `ready` event before saving jobs. `agenda.start()` will still wait for the connection to be opened.\n- `error` - called when Agenda mongo connection process has thrown an error\n\n```js\nawait agenda.start();\n```\n\n## Defining Job Processors\n\nBefore you can use a job, you must define its processing behavior.\n\n### define(jobName, fn, [options])\n\nDefines a job with the name of `jobName`. When a job of `jobName` gets run, it\nwill be passed to `fn(job, done)`. To maintain asynchronous behavior, you may\neither provide a Promise-returning function in `fn` _or_ provide `done` as a\nsecond parameter to `fn`. If `done` is specified in the function signature, you\nmust call `done()` when you are processing the job. If your function is\nsynchronous or returns a Promise, you may omit `done` from the signature.\n\n`options` is an optional argument which can overwrite the defaults. It can take\nthe following:\n\n- `concurrency`: `number` maximum number of that job that can be running at once (per instance of agenda)\n- `lockLimit`: `number` maximum number of that job that can be locked at once (per instance of agenda)\n- `lockLifetime`: `number` interval in ms of how long the job stays locked for (see [multiple job processors](#multiple-job-processors) for more info).\n  A job will automatically unlock once a returned promise resolves/rejects (or if `done` is specified in the signature and `done()` is called).\n- `priority`: `(lowest|low|normal|high|highest|number)` specifies the priority\n  of the job. Higher priority jobs will run first. See the priority mapping\n  below\n- `shouldSaveResult`: `boolean` flag that specifies whether the result of the job should also be stored in the database. Defaults to false\n\nPriority mapping:\n\n```\n{\n  highest: 20,\n  high: 10,\n  normal: 0,\n  low: -10,\n  lowest: -20\n}\n```\n\nAsync Job:\n\n```js\nagenda.define('some long running job', async job =\u003e {\n\tconst data = await doSomelengthyTask();\n\tawait formatThatData(data);\n\tawait sendThatData(data);\n});\n```\n\nAsync Job (using `done`):\n\n```js\nagenda.define('some long running job', (job, done) =\u003e {\n\tdoSomelengthyTask(data =\u003e {\n\t\tformatThatData(data);\n\t\tsendThatData(data);\n\t\tdone();\n\t});\n});\n```\n\nSync Job:\n\n```js\nagenda.define('say hello', job =\u003e {\n\tconsole.log('Hello!');\n});\n```\n\n`define()` acts like an assignment: if `define(jobName, ...)` is called multiple times (e.g. every time your script starts), the definition in the last call will overwrite the previous one. Thus, if you `define` the `jobName` only once in your code, it's safe for that call to execute multiple times.\n\n## Creating Jobs\n\n### every(interval, name, [data], [options])\n\nRuns job `name` at the given `interval`. Optionally, data and options can be passed in.\nEvery creates a job of type `single`, which means that it will only create one\njob in the database, even if that line is run multiple times. This lets you put\nit in a file that may get run multiple times, such as `webserver.js` which may\nreboot from time to time.\n\n`interval` can be a human-readable format `String`, a [cron format](https://www.npmjs.com/package/cron-parser) `String`, or a `Number`.\n\n`data` is an optional argument that will be passed to the processing function\nunder `job.attrs.data`.\n\n`options` is an optional argument that will be passed to [`job.repeatEvery`](#repeateveryinterval-options).\nIn order to use this argument, `data` must also be specified.\n\nReturns the `job`.\n\n```js\nagenda.define('printAnalyticsReport', async job =\u003e {\n\tconst users = await User.doSomethingReallyIntensive();\n\tprocessUserData(users);\n\tconsole.log('I print a report!');\n});\n\nagenda.every('15 minutes', 'printAnalyticsReport');\n```\n\nOptionally, `name` could be array of job names, which is convenient for scheduling\ndifferent jobs for same `interval`.\n\n```js\nagenda.every('15 minutes', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);\n```\n\nIn this case, `every` returns array of `jobs`.\n\n### schedule(when, name, [data])\n\nSchedules a job to run `name` once at a given time. `when` can be a `Date` or a\n`String` such as `tomorrow at 5pm`.\n\n`data` is an optional argument that will be passed to the processing function\nunder `job.attrs.data`.\n\nReturns the `job`.\n\n```js\nagenda.schedule('tomorrow at noon', 'printAnalyticsReport', { userCount: 100 });\n```\n\nOptionally, `name` could be array of job names, similar to the `every` method.\n\n```js\nagenda.schedule('tomorrow at noon', [\n\t'printAnalyticsReport',\n\t'sendNotifications',\n\t'updateUserRecords'\n]);\n```\n\nIn this case, `schedule` returns array of `jobs`.\n\n### now(name, [data])\n\nSchedules a job to run `name` once immediately.\n\n`data` is an optional argument that will be passed to the processing function\nunder `job.attrs.data`.\n\nReturns the `job`.\n\n```js\nagenda.now('do the hokey pokey');\n```\n\n### create(jobName, data)\n\nReturns an instance of a `jobName` with `data`. This does _NOT_ save the job in\nthe database. See below to learn how to manually work with jobs.\n\n```js\nconst job = agenda.create('printAnalyticsReport', { userCount: 100 });\nawait job.save();\nconsole.log('Job successfully saved');\n```\n\n## Managing Jobs\n\n### jobs(mongodb-native query, mongodb-native sort, mongodb-native limit, mongodb-native skip)\n\nLets you query (then sort, limit and skip the result) all of the jobs in the agenda job's database. These are full [mongodb-native](https://github.com/mongodb/node-mongodb-native) `find`, `sort`, `limit` and `skip` commands. See mongodb-native's documentation for details.\n\n```js\nconst jobs = await agenda.jobs({ name: 'printAnalyticsReport' }, { data: -1 }, 3, 1);\n// Work with jobs (see below)\n```\n\n### cancel(mongodb-native query)\n\nCancels any jobs matching the passed mongodb-native query, and removes them from the database. Returns a Promise resolving to the number of cancelled jobs, or rejecting on error.\n\n```js\nconst numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' });\n```\n\nThis functionality can also be achieved by first retrieving all the jobs from the database using `agenda.jobs()`, looping through the resulting array and calling `job.remove()` on each. It is however preferable to use `agenda.cancel()` for this use case, as this ensures the operation is atomic.\n\n### disable(mongodb-native query)\n\nDisables any jobs matching the passed mongodb-native query, preventing any matching jobs from being run by the Job Processor.\n\n```js\nconst numDisabled = await agenda.disable({ name: 'pollExternalService' });\n```\n\nSimilar to `agenda.cancel()`, this functionality can be acheived with a combination of `agenda.jobs()` and `job.disable()`\n\n### enable(mongodb-native query)\n\nEnables any jobs matching the passed mongodb-native query, allowing any matching jobs to be run by the Job Processor.\n\n```js\nconst numEnabled = await agenda.enable({ name: 'pollExternalService' });\n```\n\nSimilar to `agenda.cancel()`, this functionality can be acheived with a combination of `agenda.jobs()` and `job.enable()`\n\n### purge()\n\nRemoves all jobs in the database without defined behaviors. Useful if you change a definition name and want to remove old jobs. Returns a Promise resolving to the number of removed jobs, or rejecting on error.\n\n_IMPORTANT:_ Do not run this before you finish defining all of your jobs. If you do, you will nuke your database of jobs.\n\n```js\nconst numRemoved = await agenda.purge();\n```\n\n## Starting the job processor\n\nTo get agenda to start processing jobs from the database you must start it. This\nwill schedule an interval (based on `processEvery`) to check for new jobs and\nrun them. You can also stop the queue.\n\n### start\n\nStarts the job queue processing, checking [`processEvery`](#processeveryinterval) time to see if there\nare new jobs. Must be called _after_ `processEvery`, and _before_ any job scheduling (e.g. `every`).\n\n### stop\n\nStops the job queue processing. Unlocks currently running jobs.\n\nThis can be very useful for graceful shutdowns so that currently running/grabbed jobs are abandoned so that other\njob queues can grab them / they are unlocked should the job queue start again. Here is an example of how to do a graceful\nshutdown.\n\n```js\nasync function graceful() {\n\tawait agenda.stop();\n\tprocess.exit(0);\n}\n\nprocess.on('SIGTERM', graceful);\nprocess.on('SIGINT', graceful);\n```\n\n## Multiple job processors\n\nSometimes you may want to have multiple node instances / machines process from\nthe same queue. Agenda supports a locking mechanism to ensure that multiple\nqueues don't process the same job.\n\nYou can configure the locking mechanism by specifying `lockLifetime` as an\ninterval when defining the job.\n\n```js\nagenda.define(\n\t'someJob',\n\t(job, cb) =\u003e {\n\t\t// Do something in 10 seconds or less...\n\t},\n\t{ lockLifetime: 10000 }\n);\n```\n\nThis will ensure that no other job processor (this one included) attempts to run the job again\nfor the next 10 seconds. If you have a particularly long running job, you will want to\nspecify a longer lockLifetime.\n\nBy default it is 10 minutes. Typically you shouldn't have a job that runs for 10 minutes,\nso this is really insurance should the job queue crash before the job is unlocked.\n\nWhen a job is finished (i.e. the returned promise resolves/rejects or `done` is\nspecified in the signature and `done()` is called), it will automatically unlock.\n\n## Manually working with a job\n\nA job instance has many instance methods. All mutating methods must be followed\nwith a call to `await job.save()` in order to persist the changes to the database.\n\n### repeatEvery(interval, [options])\n\nSpecifies an `interval` on which the job should repeat. The job runs at the time of defining as well in configured intervals, that is \"run _now_ and in intervals\".\n\n`interval` can be a human-readable format `String`, a [cron format](https://www.npmjs.com/package/cron-parser) `String`, or a `Number`.\n\n`options` is an optional argument containing:\n\n`options.timezone`: should be a string as accepted by [moment-timezone](https://momentjs.com/timezone/) and is considered when using an interval in the cron string format.\n\n`options.skipImmediate`: `true` | `false` (default) Setting this `true` will skip the immediate run. The first run will occur only in configured interval.\n\n`options.startDate`: `Date` the first time the job runs, should be equal or after the start date.\n\n`options.endDate`: `Date` the job should not repeat after the endDate. The job can run on the end-date itself, but not after that.\n\n`options.skipDays`: `human readable string` ('2 days'). After each run, it will skip the duration of 'skipDays'\n\n```js\njob.repeatEvery('10 minutes');\nawait job.save();\n```\n\n```js\njob.repeatEvery('3 minutes', {\n\tskipImmediate: true\n});\nawait job.save();\n```\n\n```js\njob.repeatEvery('0 6 * * *', {\n\ttimezone: 'America/New_York'\n});\nawait job.save();\n```\n\n### repeatAt(time)\n\nSpecifies a `time` when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples)\n\n```js\njob.repeatAt('3:30pm');\nawait job.save();\n```\n\n### schedule(time)\n\nSpecifies the next `time` at which the job should run.\n\n```js\njob.schedule('tomorrow at 6pm');\nawait job.save();\n```\n\n### priority(priority)\n\nSpecifies the `priority` weighting of the job. Can be a number or a string from\nthe above priority table.\n\n```js\njob.priority('low');\nawait job.save();\n```\n\n### setShouldSaveResult(setShouldSaveResult)\n\nSpecifies whether the result of the job should also be stored in the database. Defaults to false.\n\n```js\njob.setShouldSaveResult(true);\nawait job.save();\n```\n\nThe data returned by the job will be available on the `result` attribute after it succeeded and got retrieved again from the database, e.g. via `agenda.jobs(...)` or through the [success job event](#agenda-events)).\n\n### unique(properties, [options])\n\nEnsure that only one instance of this job exists with the specified properties\n\n`options` is an optional argument which can overwrite the defaults. It can take\nthe following:\n\n- `insertOnly`: `boolean` will prevent any properties from persisting if the job already exists. Defaults to false.\n\n```js\njob.unique({ 'data.type': 'active', 'data.userId': '123', nextRunAt: date });\nawait job.save();\n```\n\n_IMPORTANT:_ To avoid high CPU usage by MongoDB, make sure to create an index on the used fields, like `data.type` and `data.userId` for the example above.\n\n### fail(reason)\n\nSets `job.attrs.failedAt` to `now`, and sets `job.attrs.failReason` to `reason`.\n\nOptionally, `reason` can be an error, in which case `job.attrs.failReason` will\nbe set to `error.message`\n\n```js\njob.fail('insufficient disk space');\n// or\njob.fail(new Error('insufficient disk space'));\nawait job.save();\n```\n\n### run(callback)\n\nRuns the given `job` and calls `callback(err, job)` upon completion. Normally\nyou never need to call this manually.\n\n```js\njob.run((err, job) =\u003e {\n\tconsole.log(\"I don't know why you would need to do this...\");\n});\n```\n\n### save()\n\nSaves the `job.attrs` into the database. Returns a Promise resolving to a Job instance, or rejecting on error.\n\n```js\ntry {\n\tawait job.save();\n\tcosole.log('Successfully saved job to collection');\n} catch (e) {\n\tconsole.error('Error saving job to collection');\n}\n```\n\n### remove()\n\nRemoves the `job` from the database. Returns a Promise resolving to the number of jobs removed, or rejecting on error.\n\n```js\ntry {\n\tawait job.remove();\n\tconsole.log('Successfully removed job from collection');\n} catch (e) {\n\tconsole.error('Error removing job from collection');\n}\n```\n\n### disable()\n\nDisables the `job`. Upcoming runs won't execute.\n\n### enable()\n\nEnables the `job` if it got disabled before. Upcoming runs will execute.\n\n### touch()\n\nResets the lock on the job. Useful to indicate that the job hasn't timed out\nwhen you have very long running jobs. The call returns a promise that resolves\nwhen the job's lock has been renewed.\n\n```js\nagenda.define('super long job', async job =\u003e {\n\tawait doSomeLongTask();\n\tawait job.touch();\n\tawait doAnotherLongTask();\n\tawait job.touch();\n\tawait finishOurLongTasks();\n});\n```\n\n## Job Queue Events\n\nAn instance of an agenda will emit the following events:\n\n- `start` - called just before a job starts\n- `start:job name` - called just before the specified job starts\n\n```js\nagenda.on('start', job =\u003e {\n\tconsole.log('Job %s starting', job.attrs.name);\n});\n```\n\n- `complete` - called when a job finishes, regardless of if it succeeds or fails\n- `complete:job name` - called when a job finishes, regardless of if it succeeds or fails\n\n```js\nagenda.on('complete', job =\u003e {\n\tconsole.log(`Job ${job.attrs.name} finished`);\n});\n```\n\n- `success` - called when a job finishes successfully\n- `success:job name` - called when a job finishes successfully\n\n```js\nagenda.on('success:send email', job =\u003e {\n\tconsole.log(`Sent Email Successfully to ${job.attrs.data.to}`);\n});\n```\n\n- `fail` - called when a job throws an error\n- `fail:job name` - called when a job throws an error\n\n```js\nagenda.on('fail:send email', (err, job) =\u003e {\n\tconsole.log(`Job failed with error: ${err.message}`);\n});\n```\n\n## Frequently Asked Questions\n\n### What is the order in which jobs run?\n\nJobs are run with priority in a first in first out order (so they will be run in the order they were scheduled AND with respect to highest priority).\n\nFor example, if we have two jobs named \"send-email\" queued (both with the same priority), and the first job is queued at 3:00 PM and second job is queued at 3:05 PM with the same `priority` value, then the first job will run first if we start to send \"send-email\" jobs at 3:10 PM. However if the first job has a priority of `5` and the second job has a priority of `10`, then the second will run first (priority takes precedence) at 3:10 PM.\n\nThe default [MongoDB sort object](https://docs.mongodb.com/manual/reference/method/cursor.sort/) is `{ nextRunAt: 1, priority: -1 }` and can be changed through the option `sort` when configuring Agenda.\n\n### What is the difference between `lockLimit` and `maxConcurrency`?\n\nAgenda will lock jobs 1 by one, setting the `lockedAt` property in mongoDB, and creating an instance of the `Job` class which it caches into the `_lockedJobs` array. This defaults to having no limit, but can be managed using lockLimit. If all jobs will need to be run before agenda's next interval (set via `agenda.processEvery`), then agenda will attempt to lock all jobs.\n\nAgenda will also pull jobs from `_lockedJobs` and into `_runningJobs`. These jobs are actively being worked on by user code, and this is limited by `maxConcurrency` (defaults to 20).\n\nIf you have multiple instances of agenda processing the same job definition with a fast repeat time you may find they get unevenly loaded. This is because they will compete to lock as many jobs as possible, even if they don't have enough concurrency to process them. This can be resolved by tweaking the `maxConcurrency` and `lockLimit` properties.\n\n### Sample Project Structure?\n\nAgenda doesn't have a preferred project structure and leaves it to the user to\nchoose how they would like to use it. That being said, you can check out the\n[example project structure](#example-project-structure) below.\n\n### Can I Donate?\n\nThanks! I'm flattered, but it's really not necessary. If you really want to, you can find my [gittip here](https://www.gittip.com/rschmukler/).\n\n### Web Interface?\n\nAgenda itself does not have a web interface built in but we do offer stand-alone web interface [Agendash](https://github.com/agenda/agendash):\n\n\u003ca href=\"https://raw.githubusercontent.com/agenda/agendash/master/job-details.png\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/agenda/agendash/master/job-details.png\" style=\"max-width:100%\" alt=\"Agendash interface\"\u003e\u003c/a\u003e\n\n### Mongo vs Redis\n\nThe decision to use Mongo instead of Redis is intentional. Redis is often used for\nnon-essential data (such as sessions) and without configuration doesn't\nguarantee the same level of persistence as Mongo (should the server need to be\nrestarted/crash).\n\nAgenda decides to focus on persistence without requiring special configuration\nof Redis (thereby degrading the performance of the Redis server on non-critical\ndata, such as sessions).\n\nUltimately if enough people want a Redis driver instead of Mongo, I will write\none. (Please open an issue requesting it). For now, Agenda decided to focus on\nguaranteed persistence.\n\n### Spawning / forking processes\n\nUltimately Agenda can work from a single job queue across multiple machines, node processes, or forks. If you are interested in having more than one worker, [Bars3s](http://github.com/bars3s) has written up a fantastic example of how one might do it:\n\n```js\nconst cluster = require('cluster');\nconst os = require('os');\n\nconst httpServer = require('./app/http-server');\nconst jobWorker = require('./app/job-worker');\n\nconst jobWorkers = [];\nconst webWorkers = [];\n\nif (cluster.isMaster) {\n\tconst cpuCount = os.cpus().length;\n\t// Create a worker for each CPU\n\tfor (let i = 0; i \u003c cpuCount; i += 1) {\n\t\taddJobWorker();\n\t\taddWebWorker();\n\t}\n\n\tcluster.on('exit', (worker, code, signal) =\u003e {\n\t\tif (jobWorkers.indexOf(worker.id) !== -1) {\n\t\t\tconsole.log(\n\t\t\t\t`job worker ${worker.process.pid} exited (signal: ${signal}). Trying to respawn...`\n\t\t\t);\n\t\t\tremoveJobWorker(worker.id);\n\t\t\taddJobWorker();\n\t\t}\n\n\t\tif (webWorkers.indexOf(worker.id) !== -1) {\n\t\t\tconsole.log(\n\t\t\t\t`http worker ${worker.process.pid} exited (signal: ${signal}). Trying to respawn...`\n\t\t\t);\n\t\t\tremoveWebWorker(worker.id);\n\t\t\taddWebWorker();\n\t\t}\n\t});\n} else {\n\tif (process.env.web) {\n\t\tconsole.log(`start http server: ${cluster.worker.id}`);\n\t\t// Initialize the http server here\n\t\thttpServer.start();\n\t}\n\n\tif (process.env.job) {\n\t\tconsole.log(`start job server: ${cluster.worker.id}`);\n\t\t// Initialize the Agenda here\n\t\tjobWorker.start();\n\t}\n}\n\nfunction addWebWorker() {\n\twebWorkers.push(cluster.fork({ web: 1 }).id);\n}\n\nfunction addJobWorker() {\n\tjobWorkers.push(cluster.fork({ job: 1 }).id);\n}\n\nfunction removeWebWorker(id) {\n\twebWorkers.splice(webWorkers.indexOf(id), 1);\n}\n\nfunction removeJobWorker(id) {\n\tjobWorkers.splice(jobWorkers.indexOf(id), 1);\n}\n```\n\n### Recovering lost Mongo connections (\"auto_reconnect\")\n\nAgenda is configured by default to automatically reconnect indefinitely, emitting an [error event](#agenda-events)\nwhen no connection is available on each [process tick](#processeveryinterval), allowing you to restore the Mongo\ninstance without having to restart the application.\n\nHowever, if you are using an [existing Mongo client](#mongomongoclientinstance)\nyou'll need to configure the `reconnectTries` and `reconnectInterval` [connection settings](http://mongodb.github.io/node-mongodb-native/3.0/reference/connecting/connection-settings/)\nmanually, otherwise you'll find that Agenda will throw an error with the message \"MongoDB connection is not recoverable,\napplication restart required\" if the connection cannot be recovered within 30 seconds.\n\n# Example Project Structure\n\nAgenda will only process jobs that it has definitions for. This allows you to\nselectively choose which jobs a given agenda will process.\n\nConsider the following project structure, which allows us to share models with\nthe rest of our code base, and specify which jobs a worker processes, if any at\nall.\n\n```\n- server.js\n- worker.js\nlib/\n  - agenda.js\n  controllers/\n    - user-controller.js\n  jobs/\n    - email.js\n    - video-processing.js\n    - image-processing.js\n   models/\n     - user-model.js\n     - blog-post.model.js\n```\n\nSample job processor (eg. `jobs/email.js`)\n\n```js\nlet email = require('some-email-lib'),\n\tUser = require('../models/user-model.js');\n\nmodule.exports = function (agenda) {\n\tagenda.define('registration email', async job =\u003e {\n\t\tconst user = await User.get(job.attrs.data.userId);\n\t\tawait email(user.email(), 'Thanks for registering', 'Thanks for registering ' + user.name());\n\t});\n\n\tagenda.define('reset password', async job =\u003e {\n\t\t// Etc\n\t});\n\n\t// More email related jobs\n};\n```\n\nlib/agenda.js\n\n```js\nconst Agenda = require('agenda');\n\nconst connectionOpts = { db: { address: 'localhost:27017/agenda-test', collection: 'agendaJobs' } };\n\nconst agenda = new Agenda(connectionOpts);\n\nconst jobTypes = process.env.JOB_TYPES ? process.env.JOB_TYPES.split(',') : [];\n\njobTypes.forEach(type =\u003e {\n\trequire('./jobs/' + type)(agenda);\n});\n\nif (jobTypes.length) {\n\tagenda.start(); // Returns a promise, which should be handled appropriately\n}\n\nmodule.exports = agenda;\n```\n\nlib/controllers/user-controller.js\n\n```js\nlet app = express(),\n\tUser = require('../models/user-model'),\n\tagenda = require('../worker.js');\n\napp.post('/users', (req, res, next) =\u003e {\n\tconst user = new User(req.body);\n\tuser.save(err =\u003e {\n\t\tif (err) {\n\t\t\treturn next(err);\n\t\t}\n\t\tagenda.now('registration email', { userId: user.primary() });\n\t\tres.send(201, user.toJson());\n\t});\n});\n```\n\nworker.js\n\n```js\nrequire('./lib/agenda.js');\n```\n\nNow you can do the following in your project:\n\n```bash\nnode server.js\n```\n\nFire up an instance with no `JOB_TYPES`, giving you the ability to process jobs,\nbut not wasting resources processing jobs.\n\n```bash\nJOB_TYPES=email node server.js\n```\n\nAllow your http server to process email jobs.\n\n```bash\nJOB_TYPES=email node worker.js\n```\n\nFire up an instance that processes email jobs.\n\n```bash\nJOB_TYPES=video-processing,image-processing node worker.js\n```\n\nFire up an instance that processes video-processing/image-processing jobs. Good for a heavy hitting server.\n\n# Debugging Issues\n\nIf you think you have encountered a bug, please feel free to report it here:\n\n[Submit Issue](https://github.com/hokify/agenda/issues/new)\n\nPlease provide us with as much details as possible such as:\n\n- Agenda version\n- Environment (OSX, Linux, Windows, etc)\n- Small description of what happened\n- Any relevant stack track\n- Agenda logs (see below)\n\n#### To turn on logging, please set your DEBUG env variable like so:\n\n- OSX: `DEBUG=\"agenda:*\" ts-node src/index.ts`\n- Linux: `DEBUG=\"agenda:*\" ts-node src/index.ts`\n- Windows CMD: `set DEBUG=agenda:*`\n- Windows PowerShell: `$env:DEBUG = \"agenda:*\"`\n\nWhile not necessary, attaching a text file with this debug information would\nbe extremely useful in debugging certain issues and is encouraged.\n\n# Known Issues\n\n#### \"Multiple order-by items are not supported. Please specify a single order-by item.\"\n\nWhen running Agenda on Azure cosmosDB, you might run into this issue caused by Agenda's sort query used for finding and locking the next job. To fix this, you can pass [custom sort option](#sortquery): `sort: { nextRunAt: 1 }`\n\n# Performance\n\nIt is recommended to set this index if you use agendash:\n\n```\ndb.agendaJobs.ensureIndex({\n    \"nextRunAt\" : -1,\n    \"lastRunAt\" : -1,\n    \"lastFinishedAt\" : -1\n}, \"agendash2\")\n```\n\nIf you have one job definition with thousand of instances, you can add this index to improve internal sorting query\nfor faster sortings\n\n```\ndb.agendaJobs.ensureIndex({\n    \"name\" : 1,\n    \"disabled\" : 1,\n    \"lockedAt\" : 1\n}, \"findAndLockDeadJobs\")\n```\n\n# Sandboxed Worker - use child processes\n\nIt's possible to start jobs in a child process, this helps for example for long running processes\nto seperate them from the main thread. For example if one process consumes too much memory and gets killed,\nit will not affect any others.\nTo use this feature, several steps are required.\n1.) create a childWorker helper.\nThe subrocess has a complete seperate context, so there are no database connections or anything else that can be shared.\nTherefore you have to ensure that all required connections and initializations are done here too. Furthermore\nyou also have to load the correct job definition so that agenda nows what code it must execute. Therefore 3 parameters\nare passed to the childWorker: name, jobId and path to the job definition.\n\nExample file can look like this:\n\nchildWorker.ts\n\n```ts\nimport 'reflect-metadata';\n\nprocess.on('message', message =\u003e {\n  if (message === 'cancel') {\n    process.exit(2);\n  } else {\n    console.log('got message', message);\n  }\n});\n\n(async () =\u003e {\n\tconst mongooseConnection = /** connect to database */\n\n  /** do other required initializations */\n\n  // get process arguments (name, jobId and path to agenda definition file)\n\tconst [, , name, jobId, agendaDefinition] = process.argv;\n\n  // set fancy process title\n\tprocess.title = `${process.title} (sub worker: ${name}/${jobId})`;\n\n  // initialize Agenda in \"forkedWorker\" mode\n\tconst agenda = new Agenda({ name: `subworker-${name}`, forkedWorker: true });\n\t// connect agenda (but do not start it)\n\tawait agenda.mongo(mongooseConnection.db as any);\n\n\tif (!name || !jobId) {\n\t\tthrow new Error(`invalid parameters: ${JSON.stringify(process.argv)}`);\n\t}\n\n  // load job definition\n  /** in this case the file is for example ../some/path/definitions.js\n  with a content like:\n  export default (agenda: Agenda, definitionOnly = false) =\u003e {\n    agenda.define(\n      'some job',\n      async (notification: {\n        attrs: { data: { dealId: string; orderId: TypeObjectId\u003cIOrder\u003e } };\n      }) =\u003e {\n        // do something\n      }\n    );\n\n    if (!definitionOnly) {\n        // here you can create scheduled jobs or other things\n    }\n\t});\n  */\n\tif (agendaDefinition) {\n\t\tconst loadDefinition = await import(agendaDefinition);\n\t\t(loadDefinition.default || loadDefinition)(agenda, true);\n\t}\n\n  // run this job now\n\tawait agenda.runForkedJob(jobId);\n\n  // disconnect database and exit\n\tprocess.exit(0);\n})().catch(err =\u003e {\n\tconsole.error('err', err);\n\tif (process.send) {\n\t\tprocess.send(JSON.stringify(err));\n\t}\n\tprocess.exit(1);\n});\n\n\n```\n\nEnsure to only define job definitions during this step, otherwise you create some\noverhead (e.g. if you create new jobs inside the defintion files). That's why I call\nthe defintion file with agenda and a second paramter that is set to true. If this\nparameter is true, I do not initialize any jobs (create jobs etc..)\n\n2.) to use this, you have to enable it on a job. Set forkMode to true:\n\n```ts\nconst job = agenda.create('some job', { meep: 1 });\njob.forkMode(true);\nawait job.save();\n```\n\n# Acknowledgements\n\n- Agenda was originally created by [@rschmukler](https://github.com/rschmukler).\n- [Agendash](https://github.com/agenda/agendash) was originally created by [@joeframbach](https://github.com/joeframbach).\n- These days Agenda has a great community of [contributors](https://github.com/hokify/agenda/graphs/contributors) around it. Join us!\n\n# License\n\n[The MIT License](LICENSE.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagenda%2Fagenda","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fagenda%2Fagenda","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagenda%2Fagenda/lists"}