### Install Node Quartz Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Install the node-quartz package using npm. This is the primary step to integrate the job scheduler into your Node.js project. ```bash npm install node-quartz ``` -------------------------------- ### Start Redis with Keyspace Notifications Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README This snippet demonstrates how to start a Redis server with the necessary configuration to enable keyspace notifications, which are crucial for Node Quartz's scheduling mechanism. It shows both local and Docker methods. ```bash # Local (requires redis-server installed): redis-server --notify-keyspace-events Ex # Or via Docker: docker run --rm -p 6379:6379 redis:7 redis-server --notify-keyspace-events Ex ``` -------------------------------- ### Example Import Statement Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/CHANGELOG Demonstrates the correct way to import the node-quartz package after internal path changes. Consumers should import from the package root. ```javascript const create = require('node-quartz') ``` -------------------------------- ### Example Processor: ok.js Source: https://context7_llms This JavaScript code snippet demonstrates a simple processor for Node Quartz. It increments a Redis counter, showcasing a successful job execution. ```javascript const redis = require('redis'); module.exports = { run: async (job, { queue, redis: redisClient }) => { await redisClient.incr('counter'); console.log(`Job ${job.id} processed successfully on queue ${queue}`); } }; ``` -------------------------------- ### Testing Node-Quartz with Redis Notifications Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Details the setup and execution of tests for the node-quartz library. It specifies the requirement to run Redis with keyspace notifications enabled and provides commands for running tests directly or via Docker Compose. The Docker Compose setup automates the process of spinning up Redis and a Node.js test runner. ```bash # Start Redis with keyspace notifications enabled redis-server --notify-keyspace-events Ex # Run tests directly npm test # Run tests using Docker Compose docker compose up --abort-on-container-exit --exit-code-from test # Or via npm script npm run test:compose # Note: The Docker Compose setup uses REDIS_URL=redis://redis:6379 by default. ``` -------------------------------- ### Node.js Job Processor Script Example Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/usage An example of a job processor script written in Node.js. This script is an asynchronous function that receives a job object as an argument. It logs the job ID and its data to the console, demonstrating how to access and process job information. ```javascript module.exports = async function(job) { console.log('processing', job.id, job.data); }; ``` -------------------------------- ### Example Processor: fail.js Source: https://context7_llms This JavaScript code snippet demonstrates a processor that intentionally fails for Node Quartz. This is useful for testing retry mechanisms and the Dead Letter Queue (DLQ). ```javascript module.exports = { run: async (job, { queue }) => { console.log(`Job ${job.id} on queue ${queue} is failing intentionally.`); throw new Error('Simulated failure'); } }; ``` -------------------------------- ### Manage Failed Job by ID Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Provides operations to get, requeue, or delete a failed job using its unique ID. ```shell failed:get|requeue-id|delete-id ``` -------------------------------- ### Node-Quartz CLI for Failed Jobs Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Provides examples of using the node-quartz command-line interface (CLI) to manage failed jobs. These commands allow listing, requeuing, deleting, purging, and exporting failed jobs, either by index or by job ID. Options include specifying the Redis connection URL and a job prefix. ```bash # List failed jobs (last 20) quartz failed:list --prefix quartz --redis redis://localhost:6379 --count 20 # Requeue a failed job by index (0-based) quartz failed:requeue --idx 0 --prefix quartz --redis redis://localhost:6379 --reset # Delete a failed job by index quartz failed:delete --idx 0 --prefix quartz --redis redis://localhost:6379 # Purge all failed jobs quartz failed:purge --prefix quartz --redis redis://localhost:6379 # Inspect a failed job by its ID quartz failed:get --id --prefix quartz --redis redis://localhost:6379 # Requeue a failed job by its ID quartz failed:requeue-id --id --prefix quartz --redis redis://localhost:6379 --reset # Delete a failed job by its ID quartz failed:delete-id --id --prefix quartz --redis redis://localhost:6379 # Export failed jobs to a file and purge the queue quartz failed:drain-to-file --out failed.json --prefix quartz --redis redis://localhost:6379 --purge # Import failed jobs from a file and requeue them quartz failed:import-from-file --in failed.json --requeue --reset ``` -------------------------------- ### Local Storage Utility Functions (JavaScript) Source: https://xjodoin.github.io/node-quartz/ Provides utility functions for interacting with local storage, including getting and setting JSON data. It uses URL scope for item keys and handles potential storage errors. ```javascript var palette = __md_get("__palette"); if (palette && palette.color) { if (" (prefers-color-scheme)" === palette.color.media) { var media = matchMedia("(prefers-color-scheme: light)"), input = document.querySelector(media.matches ? "[data-md-color-media='(prefers-color-scheme: light)']" : "[data-md-color-media='(prefers-color-scheme: dark)']"); palette.color.media = input.getAttribute("data-md-color-media"); palette.color.scheme = input.getAttribute("data-md-color-scheme"); palette.color.primary = input.getAttribute("data-md-color-primary"); palette.color.accent = input.getAttribute("data-md-color-accent"); } for (var [key, value] of Object.entries(palette.color)) { document.body.setAttribute("data-md-color-" + key, value); } } ``` -------------------------------- ### Node.js: Job Processor Implementation Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Provides examples of how to implement a job processor function in Node.js. The processor can be synchronous, callback-based, or asynchronous (Promise-based) and receives job data as an argument. ```javascript // /my/scripts/path/scriptToRun.js module.exports = function (job, done) { // access job.data if you provided it console.log('processing job', job.id, job.data); // do work, then call done(err?) done(); }; // or, Promise/async style // module.exports = async function (job) { // console.log('processing job', job.id, job.data); // // await work // }; ``` -------------------------------- ### Tab Element Activation (JavaScript) Source: https://xjodoin.github.io/node-quartz/ Activates tab elements based on their associated IDs in the URL hash. It checks if the target element exists and its name starts with '__tabbed_' to determine activation. ```javascript var target = document.getElementById(location.hash.slice(1)); target && target.name && (target.checked = target.name.startsWith("__tabbed_")); ``` -------------------------------- ### List Job Definitions Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Lists all currently defined job configurations. ```shell quartz defs:list ``` -------------------------------- ### MkDocs Material Configuration (JSON) Source: https://xjodoin.github.io/node-quartz/ Configuration object for MkDocs Material theme, specifying base path, features like navigation tabs and code copying, search worker script, and translation strings. ```json { "base": ".", "features": [ "navigation.tabs", "content.code.copy", "content.action.edit", "toc.integrate" ], "search": "assets/javascripts/workers/search.973d3a69.min.js", "tags": null, "translations": { "clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version" }, "version": null } ``` -------------------------------- ### Node.js: Initialize and Schedule Job with node-quartz Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Shows how to create an instance of node-quartz, configure it with various options including Redis connection, scripts directory, queues, and heartbeat. It then demonstrates scheduling a job with specific data and cron schedule. ```javascript const create = require('node-quartz'); const quartz = create({ scriptsDir: '/my/scripts/path', prefix: 'quartz', // optional, defaults to 'quartz' logger: console, // optional, provide your own logger (debug/info/warn/error) queues: ['high', 'default', 'low'], // optional, defaults to ['default'] heartbeat: { intervalMs: 2000, jitterMs: 500 }, // optional jittered master heartbeat // Optional: persist and sync job definitions across instances // Uncomment one of the store options below // store: { type: 'memory', jobs: [ /* preloaded Job objects */ ] }, // store: { type: 'file', path: './jobs.json' }, // store: { type: 'custom', impl: myStore }, redis: { // Prefer url form; legacy host/port also supported url: process.env.REDIS_URL || 'redis://localhost:6379' }, // Optional: provide in-memory processors map instead of requiring files // processors: { 'scriptToRun': async (job) => { /* ... */ } } }); // schedule a job (6-field cron with seconds) const job = { id: 'job_id', script: 'scriptToRun', // resolved relative to scriptsDir cron: '*/10 * * * * *', // every 10 seconds data: { any: 'payload' }, // optional payload passed to your script via job.data queue: 'high', // optional, defaults to 'default' options: { currentDate: null, endDate: new Date(Date.now() + 60 * 1000), tz: 'America/New_York' // optional, timezone for cron schedule } }; quartz.scheduleJob(job); // Later, shut down cleanly (unsubscribe and quit Redis): // await quartz.close(); ``` -------------------------------- ### Redis Configuration via CONFIG SET Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/CHANGELOG Shows an alternative method to configure Redis keyspace notifications using the CONFIG SET command, useful for dynamic configuration. ```bash CONFIG SET notify-keyspace-events Ex ``` -------------------------------- ### Node-Quartz CLI for Job Definitions Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Demonstrates the node-quartz CLI commands for managing job definitions. This includes listing all job definitions, adding a new definition from a file, removing a definition by ID, and triggering a reload of definitions across instances. It also shows how to use environment variables for configuration. ```bash # List all job definitions quartz defs:list --prefix quartz --redis redis://localhost:6379 # Add a job definition from a JSON file quartz defs:add --file job.json --prefix quartz --redis redis://localhost:6379 # Remove a job definition by its ID quartz defs:remove --id job_id --prefix quartz --redis redis://localhost:6379 # Ask instances to reload their job definitions quartz defs:reload --prefix quartz --redis redis://localhost:6379 # Using environment variables for configuration export REDIS_URL=redis://localhost:6379 export QUARTZ_PREFIX=my_quartz_jobs ``` -------------------------------- ### Theme Color Initialization (JavaScript) Source: https://xjodoin.github.io/node-quartz/ Initializes theme colors based on local storage settings, adapting to the user's preferred color scheme (light or dark). It applies attributes to the body element for styling. ```javascript var __md_scope = new URL(".", location), __md_hash = e => [...e].reduce((e, _) => (e << 5) - e + _.charCodeAt(0), 0), __md_get = (e, _ = localStorage, t = __md_scope) => JSON.parse(_.getItem(t.pathname + "." + e)), __md_set = (e, _, t = localStorage, a = __md_scope) => { try { t.setItem(a.pathname + "." + e, JSON.stringify(_)); } catch (e) {} } ``` -------------------------------- ### Redis Configuration for Keyspace Notifications Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/CHANGELOG Illustrates the Redis server configuration command required to enable keyspace notifications for expired keys, a necessary setting for the project. ```bash redis-server --notify-keyspace-events Ex ``` -------------------------------- ### Initialize and Schedule Job with Node-Quartz Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/usage Initializes the node-quartz scheduler with a configuration object and then schedules a new job. The configuration includes the directory for scripts, a prefix for jobs, a list of queues, and Redis connection details. The job to be scheduled has an ID, the script to run, a cron expression for timing, data payload, and optional end date. ```javascript const create = require('node-quartz'); const quartz = create({ scriptsDir: '/path/to/scripts', prefix: 'quartz', queues: ['default'], redis: { url: process.env.REDIS_URL || 'redis://localhost:6379' } }); const job = { id: 'example-job', script: 'myScript', cron: '*/10 * * * * *', data: { any: 'payload' }, options: { endDate: new Date(Date.now() + 60_000) } }; quartz.scheduleJob(job); ``` -------------------------------- ### Add Job Definition from File Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Adds a new job definition to the system using a JSON file containing the job configuration. ```shell quartz defs:add --file job.json ``` -------------------------------- ### Node-Quartz Custom Store Initialization Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/store Enables the use of a custom job store implementation in Node-Quartz. The provided implementation must expose `load`, `list`, `save`, and `remove` asynchronous methods for managing job definitions. ```javascript const myStore = { async load() { return [...]; }, async list() {...}, async save(job){...}, async remove(id){...} }; create({ store: { type: 'custom', impl: myStore } }); ``` -------------------------------- ### List Failed Queue Jobs Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Lists failed jobs from the queue with a specified prefix and Redis connection. It supports fetching a certain count of jobs. ```shell quartz failed:list --prefix quartz --redis redis://localhost:6379 --count 20 ``` -------------------------------- ### Quartz Factory and Job Management API Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README This section details the core methods for creating a Quartz instance and managing jobs within the system. ```APIDOC ## Factory ### Description Creates a new Quartz instance with the specified options. ### Method `create(options)` ### Parameters - **options** (object) - Optional - Configuration options for the Quartz instance. ## API Methods ### scheduleJob ### Description Schedules or enqueues a job. Supports 6-field cron with seconds. ### Method `scheduleJob(job)` ### Parameters - **job** (object) - Required - The job object to schedule. - `id` (string) - Unique identifier for the job. - `name` (string) - Name of the job. - `cron` (string) - Cron expression for scheduling. - `data` (any) - Payload for the job. - `options` (object) - Optional - Job-specific options. - `retry` (object) - Retry configuration. - `maxAttempts` (number) - Maximum number of retry attempts. - `backoff` (number | object) - Backoff strategy for retries. ### getJob ### Description Fetches the stored payload of a job by its ID. ### Method `getJob(jobId, cb)` ### Parameters - **jobId** (string) - Required - The ID of the job to fetch. - **cb** (function) - Required - Callback function `(error, jobPayload)`. ### removeJob ### Description Deletes a stored job payload by its ID. ### Method `removeJob(jobId, cb)` ### Parameters - **jobId** (string) - Required - The ID of the job to remove. - **cb** (function) - Required - Callback function `(error)`. ### listJobsKey ### Description Lists all persisted job keys for the given prefix. ### Method `listJobsKey(cb)` ### Parameters - **cb** (function) - Required - Callback function `(error, jobKeys)`. ### close ### Description Stops the worker loop and gracefully quits Redis connections. ### Method `close(cb?)` ### Parameters - **cb** (function) - Optional - Callback function `(error)`. ``` -------------------------------- ### Node-Quartz File Store Initialization Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/store Configures Node-Quartz to use a file-based job store. Job definitions are loaded from a specified JSON file. Ensure the JSON file contains an array of valid Job objects. ```javascript create({ store: { type: 'file', path: './jobs.json' } }); ``` -------------------------------- ### Node-Quartz CLI - Job Definitions Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Commands for managing job definitions via the command-line interface. ```APIDOC ## CLI - Job Definitions ### list-defs #### Description Lists all job definitions. #### Command `quartz defs:list --prefix --redis ` ### add-def #### Description Adds a job definition from a file. #### Command `quartz defs:add --file --prefix --redis ` ### remove-def #### Description Removes a job definition by its ID. #### Command `quartz defs:remove --id --prefix --redis ` ### reload-defs #### Description Asks all running instances to reload their job definitions. #### Command `quartz defs:reload --prefix --redis ` ``` -------------------------------- ### Redis Configuration for Node-Quartz Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Details the Redis connection options for node-quartz, including the preferred URL format and legacy host/port options. It also mentions the requirement for keyspace notifications. ```javascript redis: { // Prefer url form; legacy host/port also supported url: process.env.REDIS_URL || 'redis://localhost:6379', database: 6 // Defaults to 0. Keyspace notifications subscriptions use this DB for '__keyevent@__:*' } ``` -------------------------------- ### CLI: Inspect and Requeue Failed Jobs Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Demonstrates how to use the node-quartz CLI to list failed jobs and requeue a specific failed job. It requires a Redis URL and a job prefix. ```shell export REDIS_URL=redis://127.0.0.1:6379 npm run demo # 3) Inspect failed jobs (if any) with the CLI npx quartz failed:list --count 20 --redis "$REDIS_URL" --prefix quartz:test # Requeue the first failed job and reset attempts npx quartz failed:requeue --idx 0 --reset --redis "$REDIS_URL" --prefix quartz:test ``` -------------------------------- ### Import Failed Jobs from File Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Imports failed jobs from a specified JSON file into the queue. ```shell quartz failed:import-from-file --in failed.json ``` -------------------------------- ### Reload Job Definitions Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Reloads all job definitions, applying any recent changes or updates. ```shell quartz defs:reload ``` -------------------------------- ### Node-Quartz Memory Store Initialization Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/store Initializes Node-Quartz with an in-memory job store. The store is populated with an array of job objects provided during creation. This is suitable for development or simple use cases where persistence is not required. ```javascript create({ store: { type: 'memory', jobs: [ /* Job objects */ ] } }); ``` -------------------------------- ### Node-Quartz CLI - Failed Jobs Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Commands for managing failed jobs via the command-line interface. ```APIDOC ## CLI - Failed Jobs ### list #### Description Lists failed jobs. #### Command `quartz failed:list --prefix --redis --count ` ### requeue #### Description Requeues a failed job by its index in the failed list. #### Command `quartz failed:requeue --idx --prefix --redis --reset` ### delete #### Description Deletes a failed job by its index in the failed list. #### Command `quartz failed:delete --idx --prefix --redis ` ### purge #### Description Purges all jobs from the failed queue. #### Command `quartz failed:purge --prefix --redis ` ### get #### Description Inspects a failed job by its ID. #### Command `quartz failed:get --id --prefix --redis ` ### requeue-id #### Description Requeues a failed job by its ID. #### Command `quartz failed:requeue-id --id --prefix --redis --reset` ### delete-id #### Description Deletes a failed job by its ID. #### Command `quartz failed:delete-id --id --prefix --redis ` ### drain-to-file #### Description Exports failed jobs to a file. #### Command `quartz failed:drain-to-file --out --prefix --redis --purge` ### import-from-file #### Description Imports failed jobs from a file. #### Command `quartz failed:import-from-file --in --prefix --redis ` ### import-from-file-requeue #### Description Imports failed jobs from a file and attempts to requeue them. #### Command `quartz failed:import-from-file --in --requeue --reset` ``` -------------------------------- ### Export Failed Jobs to File Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Exports failed jobs to a specified JSON file and optionally purges them from the queue after export. ```shell quartz failed:drain-to-file --out failed.json --purge ``` -------------------------------- ### Node.js Job Scheduling API Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Demonstrates the core API methods for interacting with the node-quartz scheduler in a Node.js environment. It covers scheduling, retrieving, removing, and listing jobs, as well as closing the scheduler and handling events. The library uses node-redis v4 (async). ```javascript const quartz = require('node-quartz'); // Factory to create a quartz instance const scheduler = quartz.create({ // options }); // Schedule a job scheduler.scheduleJob({ // job details }); // Get job details scheduler.getJob('jobId', (err, job) => { // handle job }); // Remove a job scheduler.removeJob('jobId', (err) => { // handle removal }); // List job keys scheduler.listJobsKey((err, keys) => { // handle keys }); // Close the scheduler scheduler.close((err) => { // handle closing }); // Event listeners scheduler.events.on('scheduled', (job, nextDate) => { console.log('Job scheduled:', job.id, 'Next run:', nextDate); }); scheduler.events.on('failed', (job, error) => { console.error('Job failed:', job.id, 'Error:', error); }); ``` -------------------------------- ### Quartz Events Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/README Details the events emitted by the Quartz instance for monitoring job lifecycle. ```APIDOC ## Events ### Description The `quartz.events` object is an EventEmitter that emits various events related to job processing. ### Emitted Events - **scheduled** - **Description**: Emitted when a job is scheduled. - **Parameters**: `(job, nextDate)` - **started** - **Description**: Emitted when a job execution starts. - **Parameters**: `(job)` - **succeeded** - **Description**: Emitted when a job execution succeeds. - **Parameters**: `(job)` - **failed** - **Description**: Emitted when a job execution fails. - **Parameters**: `(job, error)` - **retryScheduled** - **Description**: Emitted when a job is scheduled for retry. - **Parameters**: `(job, delayMs)` ``` -------------------------------- ### Requeue Failed Job by Index Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Requeues a specific failed job identified by its index. The `--reset` flag can be used to reset the job's state. ```shell quartz failed:requeue --idx 0 --reset ``` -------------------------------- ### Delete Failed Job by Index Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Deletes a specific failed job identified by its index from the queue. ```shell quartz failed:delete --idx 0 ``` -------------------------------- ### Remove Job Definition by ID Source: https://raw.githubusercontent.com/xjodoin/node-quartz/master/docs/cli Removes a specific job definition identified by its unique ID. ```shell quartz defs:remove --id job_id ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.