### Installing Pulse Library (npm) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Instructions to install the `@pulsecron/pulse` job queue library using the npm package manager. This command adds the library as a dependency to your project, making it available for use in your applications. ```bash npm i @pulsecron/pulse ``` -------------------------------- ### Handling Job Lifecycle Events (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Demonstrates how to listen for and react to various job lifecycle events using `pulse.on()`. It includes examples for 'start', 'success', and 'fail' events, allowing for logging or other actions based on job status. A helper `time()` function is also included for timestamping logs. ```typescript /** * Check job start and completion/failure */ pulse.on('start', (job) => { console.log(time(), `Job <${job.attrs.name}> starting`); }); pulse.on('success', (job) => { console.log(time(), `Job <${job.attrs.name}> succeeded`); }); pulse.on('fail', (error, job) => { console.log(time(), `Job <${job.attrs.name}> failed:`, error); }); function time() { return new Date().toTimeString().split(' ')[0]; } ``` -------------------------------- ### Scheduling a One-Time Job (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Demonstrates how to schedule a job to run at a specific future time using `pulse.schedule()`. This example schedules the 'send email report' job to run in 20 minutes, passing `to: 'admin@example.com'` as job data. ```typescript /** * Example of scheduling a job */ (async function () { await pulse.start(); await pulse.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' }); })(); ``` -------------------------------- ### Activating Pulse Job Queue with `start()` in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-job-processor/start.md This TypeScript example illustrates the essential steps to initialize the Pulse library, configure the job processing interval using `processEvery(100)`, and then activate the job queue with `pulse.start()`. It also demonstrates scheduling a daily report job using `pulse.every()` after the queue has been started, highlighting the correct order of operations. ```typescript const pulse = new Pulse(); pulse.processEvery(100); pulse.start(); // It should be in this position See NOTES section at the page pulse.every('1 day', 'dailyReport', { reportId: 123 }); ``` -------------------------------- ### Initializing Pulse with MongoDB Connection (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Demonstrates how to initialize the Pulse job queue instance, connecting it to a MongoDB database. It shows various options for specifying the database connection string, overriding the collection name, passing additional connection options, or using an existing MongoClient instance. ```typescript import Pulse from '@pulsecron/pulse'; const mongoConnectionString = 'mongodb://localhost:27017/pulse'; const pulse = new Pulse({ db: { address: mongoConnectionString } }); // Or override the default collection name: // const pulse = new Pulse({db: {address: mongoConnectionString, collection: 'jobCollectionName'}}); // or pass additional connection options: // const pulse = new Pulse({db: {address: mongoConnectionString, collection: 'jobCollectionName', options: {ssl: true}}}); // or pass in an existing mongodb-native MongoClient instance // const pulse = new Pulse({mongo: myMongoClient}); ``` -------------------------------- ### Defining a Basic Job with Options (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Illustrates how to define a new job named 'delete old users' using `pulse.define()`. This example includes job options such as `shouldSaveResult` to store the job's outcome, `attempts` for retries, and `backoff` for exponential delay between retries. ```typescript /** * Example of defining a job */ pulse.define('delete old users', async (job) => { console.log('Deleting old users...'); return; }, { shouldSaveResult: true, attempts: 4, backoff: { type: 'exponential', delay: 1000 } }); ``` -------------------------------- ### Repeating a Job with `create` and `repeatEvery` (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Shows an alternative way to create and repeat a job using the `pulse.create()` method. This approach allows for chaining `repeatEvery()` to set a recurring schedule (e.g., '1 week') and then `save()` to persist the job. ```typescript /** * Example of repeating a job */ (async function () { const weeklyReport = pulse.create('send email report', { to: 'example@example.com' }); await pulse.start(); await weeklyReport.repeatEvery('1 week').save(); })(); ``` -------------------------------- ### Repeating a Job with `every` (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Shows how to set up a job to repeat at regular intervals using `pulse.every()`. It demonstrates repeating the 'delete old users' job every 3 minutes, accepting both human-readable intervals and cron-style expressions. The `pulse.start()` method is called to begin processing jobs. ```typescript /** * Example of repeating a job */ (async function () { // IIFE to give access to async/await await pulse.start(); await pulse.every('3 minutes', 'delete old users'); // Alternatively, you could also do: await pulse.every('*/3 * * * *', 'delete old users'); })(); ``` -------------------------------- ### Defining a Job with Data and Advanced Options (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/quick-start.md Defines a 'send email report' job that processes data passed to it, specifically a `to` recipient. It includes advanced options like `lockLifetime` to control how long a job is locked during execution, `priority` for scheduling, and `concurrency` to limit simultaneous executions. ```typescript /** * Example of defining a job with options */ pulse.define( 'send email report', async (job) => { const { to } = job.attrs.data; console.log(`Sending email report to ${to}`); }, { lockLifetime: 5 * 1000, priority: 'high', concurrency: 10 } ); ``` -------------------------------- ### Installing Pulse via npm Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet demonstrates how to install the `@pulsecron/pulse` library using npm. It adds the package as a dependency to your project, allowing you to use its job scheduling and management functionalities. ```console $ npm install --save @pulsecron/pulse ``` -------------------------------- ### Scheduling an Immediate Job using pulse.now (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/creating-jobs/now.md This example illustrates how to use the `pulse.now` method to schedule a job for immediate execution. It first instantiates a `Pulse` object and then invokes `pulse.now` with a job name 'urgentUpdate' and an object containing `updateDetails`, demonstrating its use for high-priority tasks. ```TypeScript const pulse = new Pulse(); // Schedule a job to run immediately to handle a high priority update pulse.now('urgentUpdate', { updateDetails: 'Fix critical security issue' }) ``` -------------------------------- ### Cloning Pulse Repository (Shell) Source: https://github.com/pulsecron/pulse/blob/main/README.md This command clones the Pulse project repository from GitHub to your local machine, allowing you to start working on the codebase. It creates a local copy of the entire repository. ```Shell git clone https://github.com/pulsecron/pulse ``` -------------------------------- ### Enabling and Saving a PulseCron Job in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-10.md This TypeScript example demonstrates how to create a new job using `pulse.create()`, activate it with `job.enable()`, and then persist its state to the database using `job.save()`. Enabling a job makes it eligible for execution, while saving ensures its configuration is retained across sessions. ```typescript const job = pulse.create('test', {}); job.enable(); job.save(); // If you want to save it ``` -------------------------------- ### Saving a Newly Created Job in Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/save.md This example demonstrates how to initialize a new Pulse instance, create a job with specific parameters, and then use the `job.save()` method to commit the job's initial state to the MongoDB database. This ensures the job's configuration and details are persistently stored. ```typescript const pulse = new Pulse(); const job = pulse.create('delete old users', { to: 'pulsecron@gmail.com' }); job.save(); ``` -------------------------------- ### Handling Pulse Job Events Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet shows how to listen for and react to various Pulse job lifecycle events: `start`, `success`, and `fail`. It logs messages to the console indicating when a job begins, completes successfully, or encounters an error, providing real-time monitoring capabilities. A helper `time()` function is included for timestamping logs. ```typescript /** * Check job start and completion/failure */ pulse.on('start', (job) => { console.log(time(), `Job <${job.attrs.name}> starting`); }); pulse.on('success', (job) => { console.log(time(), `Job <${job.attrs.name}> succeeded`); }); pulse.on('fail', (error, job) => { console.log(time(), `Job <${job.attrs.name}> failed:`, error); }); function time() { return new Date().toTimeString().split(' ')[0]; } ``` -------------------------------- ### Deleting a Job with `job.remove()` (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-3.md This TypeScript example illustrates the usage of the `job.remove()` method to delete a job. A job is first created using `pulse.create()`, and then `job.remove()` is invoked on the created job instance to remove it from the MongoDB database. This operation is asynchronous and returns a promise. ```typescript const job = pulse.create('test', {}); job.remove(); ``` -------------------------------- ### Enabling Jobs with Pulse.enable (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/enable.md This snippet demonstrates how to use the `pulse.enable` method in TypeScript to re-enable jobs. It shows an example of enabling all jobs that were disabled for a 'maintenance' reason by providing a MongoDB filter query. The method returns a promise that resolves with the count of modified job records. ```typescript const pulse = new Pulse(); // Example of enabling all jobs that were disabled for a maintenance window const maintenanceQuery = { reason: 'maintenance' }; pulse.enable(maintenanceQuery) .then(modifiedCount => console.log(`${modifiedCount} jobs re-enabled after maintenance`)) .catch(error => console.error('Failed to enable jobs:', error)); ``` -------------------------------- ### Failing a Job in PulseCron (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-7.md This example demonstrates how to mark a job as failed using `job.fail()` in PulseCron. It shows creating a new job, calling `fail()` with an `Error` object as the reason, and then explicitly calling `save()` to persist the failure status to the database. The `save()` call is crucial as `fail()` itself does not save the job. ```TypeScript const job = pulse.create('test', {}); job.fail(new Error('Unable to connect to database')); job.save(); // If you want to save it ``` -------------------------------- ### Scheduling a PulseCron Job with a Date Object (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-2.md This example illustrates how to schedule a new job in PulseCron by providing a `Date` object to the `job.schedule()` method. After scheduling, the job's `nextRunAt` property is updated. It's important to call `await job.save()` afterwards to persist the scheduled job to the database, as `schedule()` itself does not save the job. ```typescript const job = pulse.create('test', {}); job.schedule(new Date(2023, 11, 17, 10, 30)); await job.save(); // If you want to save it ``` -------------------------------- ### Updating Job Lock Timestamp with `job.touch()` in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-5.md This example demonstrates how to use the `job.touch()` method to update the `lockedAt` timestamp of a job. It creates a new job named 'test' and then calls `touch()` with an optional progress value of 10, ensuring the job remains locked during its execution and preventing it from being considered timed out. ```typescript const job = pulse.create('test', {}); job.touch(10); ``` -------------------------------- ### Initializing Pulse with MongoDB Connection Configuration (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/connection.md This snippet demonstrates how to initialize a new Pulse instance by defining its configuration, including the polling interval (`processEvery`), maximum concurrent jobs (`maxConcurrency`), and MongoDB connection details (`db.address`, `db.collection`). It also shows how to handle the connection callback to log success or error. ```typescript const pulseConfig = { processEvery: '1 minute', maxConcurrency: 10, db: { address: 'mongodb://localhost:27017/myApp', collection: 'jobQueue' } }; const pulse = new Pulse(pulseConfig, (error, collection) => { if (error) { console.error('Connection error:', error); } else { console.log('Connected to MongoDB collection:', collection.collectionName); } }); ``` -------------------------------- ### Scheduling Single and Multiple Jobs with Pulse.every (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/creating-jobs/every.md This snippet demonstrates how to use the `pulse.every` method to schedule both a single job (`dailyReport`) to run daily and multiple jobs (`updateCache`, `refreshData`) to run every 30 minutes. It shows passing data to a job and using options like `skipImmediate` to control initial execution. Dependencies include an initialized `Pulse` instance. ```typescript const pulse = new Pulse(); pulse.start() // Set a custom sort order for job processing pulse.every('1 day', 'dailyReport', { reportId: 123 }); // Schedule multiple jobs to run every 30 minutes pulse.every('30 minutes', ['updateCache', 'refreshData'], null, { skipImmediate: true }); ``` -------------------------------- ### Creating and Saving a Pulse Job (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery.md This snippet demonstrates the initial steps to create a new job instance using `pulse.create`, apply a uniqueness constraint to prevent duplicate jobs, and then persist the job to the database using `job.save()`. Saving the job is essential for its persistence and execution. ```typescript const job = pulse.create('test', {}); job.unique({ 'data.type': 'email', 'data.userId': '12345' }); await job.save(); // If you want to save it ``` -------------------------------- ### Repeating a Pulse Job with `create` and `repeatEvery` Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet demonstrates an alternative way to repeat a job by first creating a job instance with `pulse.create()`, then chaining `repeatEvery('1 week')`, and finally calling `save()`. This approach provides more granular control over job creation and repetition. ```typescript /** * Example of repeating a job */ (async function () { const weeklyReport = pulse.create('send email report', { to: 'example@example.com' }); await pulse.start(); await weeklyReport.repeatEvery('1 week').save(); })(); ``` -------------------------------- ### Configuring Job Resumption on Restart with Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/sort-1.md This snippet demonstrates how to configure the `Pulse` instance to resume unfinished jobs after a system restart. It shows both setting the `resumeOnRestart` flag via a method call and initializing it directly in the `Pulse` constructor. The method ensures continuity of job processing by resuming jobs that were in progress or awaiting execution. ```TypeScript const pulse = new Pulse(); pulse.resumeOnRestart(true) // or pulse.resumeOnRestart() //or new Pulse({ resumeOnRestart: true }); ``` -------------------------------- ### Initializing Pulse with MongoDB Connection Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet initializes a new Pulse instance, connecting it to a MongoDB database. It configures the database address, default and maximum concurrency, job processing interval, and enables resuming jobs on restart. It also shows commented-out options for overriding the collection name, passing additional connection options, or using an existing MongoClient instance. ```typescript import Pulse from '@pulsecron/pulse'; const mongoConnectionString = 'mongodb://localhost:27017/pulse'; const pulse = new Pulse({ db: { address: mongoConnectionString }, defaultConcurrency: 4, maxConcurrency: 4, processEvery: '10 seconds', resumeOnRestart: true, }); // Or override the default collection name: // const pulse = new Pulse({db: {address: mongoConnectionString, collection: 'jobCollectionName'}}); // or pass additional connection options: // const pulse = new Pulse({db: {address: mongoConnectionString, collection: 'jobCollectionName', options: {ssl: true}}}); // or pass in an existing mongodb-native MongoClient instance // const pulse = new Pulse({mongo: myMongoClient}); ``` -------------------------------- ### Creating a New Job Instance with Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/creating-jobs/create.md This snippet demonstrates how to create a new job instance using `pulse.create()`. It initializes a `Pulse` object and then creates a job named 'dataAnalysis' with specific `datasetId` data. It also shows the optional `save()` call to persist the job, emphasizing that creation alone does not save it. ```typescript const pulse = new Pulse(); // Create a new job for data analysis const analysisJob = pulse.create('dataAnalysis', { datasetId: 101 }); analysisJob.save() // If you want to save it ``` -------------------------------- ### Scheduling a Job to Repeat at a Specific Time with Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-1.md This snippet demonstrates how to use the `repeatAt` method to schedule a job to run daily at 5:00 PM (17:00). It highlights the creation of a new job, setting its repetition time, and the critical step of calling `await job.save()` to ensure the job's configuration is persisted in the database. The `time` parameter accepts human-readable formats. ```TypeScript const job = pulse.create('test', {}); job.repeatAt("17:00"); await job.save(); // If you want to save it ``` -------------------------------- ### Querying Completed Jobs with Pulse.jobs (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/jobs.md This snippet demonstrates how to use the `pulse.jobs` method to fetch a paginated and sorted list of completed jobs. It filters for jobs with `status: 'completed'`, sorts them by `createdAt` in descending order, limits the results to 10, and skips the first 5 records. The promise resolves with an array of `Job` objects or catches any errors during the fetch operation. ```TypeScript const pulse = new Pulse(); // Fetch the first 10 completed jobs, skipping the first 5, sorted by creation date pulse.jobs({ status: 'completed' }, { createdAt: -1 }, 10, 5) .then(jobs => { console.log('Retrieved completed jobs:', jobs); }) .catch(error => { console.error('Error fetching jobs:', error); }); ``` -------------------------------- ### Scheduling Jobs with Pulse Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/creating-jobs/schedule.md This snippet demonstrates how to use the `pulse.schedule` method to schedule both a single job at a precise future `Date` object and multiple jobs using a descriptive time string. It shows how to calculate a specific future date (next Monday) and pass optional data to the scheduled job. ```typescript const pulse = new Pulse(); // Schedule a single job to run next Monday at 9 AM const nextMonday = new Date(); nextMonday.setDate(nextMonday.getDate() + ((1 + 7 - nextMonday.getDay()) % 7 || 7)); nextMonday.setHours(9, 0, 0, 0); pulse.schedule(nextMonday, 'weeklyMeetingReminder', { meetingId: 456 }); pulse.schedule('tomorrow at noon', [ 'printAnalyticsReport', 'sendNotifications', 'updateUserRecords' ]); ``` -------------------------------- ### Repeating a Pulse Job Periodically Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet shows how to repeat a defined job, 'delete old users', every 3 minutes using `pulse.every()`. It also illustrates an alternative using a cron string. The `pulse.start()` method is called first to begin processing jobs. ```typescript /** * Example of repeating a job */ (async function () { // IIFE to give access to async/await await pulse.start(); await pulse.every('3 minutes', 'delete old users'); // Alternatively, you could also do: await pulse.every('*/3 * * * *', 'delete old users'); })(); ``` -------------------------------- ### Pushing Git Branch to Origin (Shell) Source: https://github.com/pulsecron/pulse/blob/main/README.md This command pushes the local 'new-feature-x' branch and its commits to the remote repository on GitHub. This makes your changes available online for review and potential pull requests. ```Shell git push origin new-feature-x ``` -------------------------------- ### Executing a Job with job.run() in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-8.md This snippet demonstrates how to execute a job using the `job.run()` method. It shows handling both successful completion and errors via Promises, logging the outcome to the console. This method is typically called internally by the system. ```TypeScript const job = pulse.create('test', {}); job.run() .then(() => console.log('Job execution completed.')) .catch(error => console.error('Job execution failed:', error)); ``` -------------------------------- ### Configuring Job Processing Interval with Pulse.processEvery (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/processevery.md This snippet demonstrates how to configure the job processing interval for a `Pulse` instance. It shows two ways: by calling the `processEvery` method after instantiation, and by passing the interval directly to the `Pulse` constructor. The interval dictates how often Pulse queries the database for jobs to process. ```TypeScript const pulse = new Pulse(); // Configure the job processing interval to every 10 minutes pulse.processEvery('10 minutes'); //or new Pulse({ processEvery:'10 minutes' }); ``` -------------------------------- ### Scheduling a Pulse Job for a Specific Time Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet illustrates how to schedule the 'send email report' job to run once 'in 20 minutes' using `pulse.schedule()`. It passes data (`{ to: 'admin@example.com' }`) to the job, which will be accessible within the job's handler. ```typescript /** * Example of scheduling a job */ (async function () { await pulse.start(); await pulse.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' }); })(); ``` -------------------------------- ### Defining a Basic Pulse Job Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet demonstrates how to define a new job named 'delete old users' using `pulse.define()`. The job's handler is an asynchronous function that logs a message to the console. This sets up the job for later scheduling or repetition. ```typescript /** * Example of defining a job */ pulse.define('delete old users', async (job) => { console.log('Deleting old users...'); return; }); ``` -------------------------------- ### Creating a New Git Branch (Shell) Source: https://github.com/pulsecron/pulse/blob/main/README.md This command creates and switches to a new Git branch named 'new-feature-x'. It's crucial to work on a separate branch to isolate your changes and avoid directly affecting the main codebase until your changes are ready for integration. ```Shell git checkout -b new-feature-x ``` -------------------------------- ### Defining a Pulse Job with Custom Options Source: https://github.com/pulsecron/pulse/blob/main/README.md This snippet defines a job 'send email report' that accepts data (e.g., `to` address) and logs it. It demonstrates how to configure job-specific options like `lockLifetime`, `priority`, and `concurrency`, which control the job's execution behavior. ```typescript /** * Example of defining a job with options */ pulse.define( 'send email report', async (job) => { const { to } = job.attrs.data; console.log(`Sending email report to ${to}`); }, { lockLifetime: 5 * 1000, priority: 'high', concurrency: 10 } ); ``` -------------------------------- ### Setting Global Max Concurrency in Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/maxconcurrency.md This snippet demonstrates how to set the maximum number of concurrent jobs for a `Pulse` instance using the `maxConcurrency` method. It shows both setting the concurrency after instantiation and as an option during `Pulse` object creation, ensuring overall system load is controlled. ```typescript const pulse = new Pulse(); // Set the default concurrency for job processing to 3 pulse.maxConcurrency(10); //or new Pulse({ maxConcurrenc: 10 }); ``` -------------------------------- ### Setting Job Priority with `job.priority()` in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-4.md This snippet illustrates how to create a new job, set its priority to 'highest' using the `job.priority()` method, and then save the job to the database. The `save()` method is essential for persisting the priority change. ```TypeScript const job = pulse.create('test', {}); job.priority('highest'); job.save(); // If you want to save it ``` -------------------------------- ### Purging Undefined Jobs with Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/purge.md This snippet demonstrates how to initialize a `Pulse` instance, define two asynchronous job types ('emailNotification' and 'dataBackup'), and then invoke the `purge()` method. The `purge()` method removes any jobs from the system that do not correspond to the currently defined types, logging the count of deleted jobs or an error if the operation fails. ```typescript const pulse = new Pulse(); pulse.define('emailNotification', async (job) => { // Processing logic here }); pulse.define('dataBackup', async (job) => { // Processing logic here }); // Remove all jobs that are not defined as 'emailNotification' or 'dataBackup' pulse.purge() .then(deletedCount => console.log(`${deletedCount} undefined jobs purged from the system`)) .catch(error => console.error('Failed to purge jobs:', error)); ``` -------------------------------- ### Setting Job Queue Name with Pulse.name in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/name.md This snippet demonstrates how to set or update the name of a Pulse instance's job queue. It shows two ways: calling the `name` method on an existing instance or passing the name directly during instantiation. The name is used for identification and management of the queue. ```TypeScript const pulse = new Pulse(); pulse.name('emailProcessingQueue'); //or new Pulse({ name:'emailProcessingQueue' }); ``` -------------------------------- ### Setting Job Result Persistence in PulseCron (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-6.md This snippet demonstrates how to use the `setShouldSaveResult` method to configure a job to save its execution results. It also shows the necessary `save()` call to persist the job configuration itself to the database. The `pulse.create` method initializes a new job instance. ```TypeScript const job = pulse.create('test', {}); job.setShouldSaveResult(true); job.save(); // If you want to save it ``` -------------------------------- ### Setting Default Lock Limit with Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/defaultlocklimit.md This snippet demonstrates how to set the default concurrency limit for job processing using the `defaultLockLimit` method on a `Pulse` instance. It shows both direct method invocation and initialization via the constructor, allowing a maximum of 2 concurrent locks for any job type. ```TypeScript const pulse = new Pulse(); // Set the default concurrency for job processing to 3 pulse.defaultLockLimit(2); //or new Pulse({ defaultLockLimit: 2 }); ``` -------------------------------- ### Canceling Jobs with Specific Priority using Pulse.cancel (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/cancel.md This snippet demonstrates how to use the `pulse.cancel` method to remove jobs from the database that match a specific MongoDB query. It initializes a `Pulse` instance and then calls `cancel` with a query to delete jobs having a negative priority. The method returns a promise that resolves with the count of deleted jobs or rejects on error. ```TypeScript const pulse = new Pulse(); // Example of canceling all jobs with a specific priority const query = { priority: { $lt: 0 } }; // Cancels all jobs with a negative priority pulse.cancel(query) .then(deletedCount => console.log(`${deletedCount} low priority jobs cancelled`)) .catch(error => console.error('Failed to cancel jobs:', error)); ``` -------------------------------- ### Configuring Unique Job with Pulse and MongoDB Filter (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/unique.md This snippet demonstrates how to configure a job to be unique using the `job.unique` method in Pulse. It applies a MongoDB filter to ensure no other job with the same `data.type` and `data.userId` exists. The `await job.save()` line shows how to persist the job after applying uniqueness. ```TypeScript const job = pulse.create('test', {}); job.unique({ 'data.type': 'email', 'data.userId': '12345' }); await job.save(); // If you want to save it ``` -------------------------------- ### Setting Custom Sort Order for Pulse Jobs (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/sort.md This snippet demonstrates how to configure a custom sort order for jobs using the `pulse.sort()` method or by passing the sort option directly during `Pulse` initialization. It shows sorting by `createdAt` in descending order, affecting job processing priority. ```TypeScript const pulse = new Pulse(); // Set a custom sort order for job processing pulse.sort({ createdAt: -1 }); //or new Pulse({ sort: { createdAt: -1 } }); ``` -------------------------------- ### Setting Global Job Lock Limit in Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/locklimit.md This snippet demonstrates how to configure the global job lock limit for a `Pulse` instance. The `lockLimit` method or constructor option sets the maximum number of jobs that can be locked concurrently, preventing system overload. The `limit` parameter specifies this maximum number, and the method returns the `Pulse` instance for chaining. ```typescript const pulse = new Pulse(); // Set a global lock limit to prevent too many jobs from being locked at the same time pulse.lockLimit(5); //or new Pulse({ lockLimit: 5 }); ``` -------------------------------- ### Committing Changes to Git (Shell) Source: https://github.com/pulsecron/pulse/blob/main/README.md This command commits your staged changes to the local repository with a descriptive message. A clear commit message helps in understanding the purpose of the changes later. ```Shell git commit -m 'Implemented new feature x.' ``` -------------------------------- ### Defining an Email Sending Job with Pulse Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/defining-job-processors.md This snippet demonstrates how to define a 'sendEmail' job type using `pulse.define`. It includes an asynchronous processor function that simulates sending an email and handles success or failure using the `done` callback. The definition also configures advanced options like concurrency, lock limits, priority, result saving, and exponential retry attempts. ```TypeScript const pulse = new Pulse(); // Define a job type for sending emails pulse.define('sendEmail', async (job, done) => { try { await sendEmail(job.data); // Mark the job as completed done(); // or done(undefined, 'Success'); } catch (error) { console.error('Failed to send email:', error); done(error); } }, { concurrency: 5, lockLimit: 2, priority: 'high', lockLifetime: 300000, // 5 minutes shouldSaveResult: true, attempts: 5, // Retry up to 5 times backoff: { type: 'exponential', delay: 2000, // Start with a 2-second delay between retries }, }); ``` -------------------------------- ### Setting Default Job Lock Lifetime in Pulse (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/defaultlocklifetime.md This snippet demonstrates how to configure the default lock lifetime for jobs using the `Pulse` library. It shows both setting the lifetime via a method call on an existing `Pulse` instance and an alternative approach during instance initialization. This duration determines how long a job remains locked during processing before automatic release, aiding in job recovery. ```TypeScript const pulse = new Pulse(); // Set the default lock lifetime to 5 minutes (300000 ms) pulse.defaultLockLifetime(300000); //or new Pulse({ defaultLockLifetime: 300000 }); ``` -------------------------------- ### Setting Default Concurrency for Pulse Instance (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/setup-and-config/config/defaultconcurrency.md This snippet demonstrates how to set the default concurrency for a `Pulse` instance. It shows two ways: using the `defaultConcurrency` method on an existing instance or by passing the `defaultConcurrency` option during `Pulse` instance creation. This setting limits the number of jobs processed concurrently, affecting resource utilization and job throughput. ```typescript const pulse = new Pulse(); // Set the default concurrency for job processing to 3 pulse.defaultConcurrency(3); //or new Pulse({ defaultConcurrency: 3 }); ``` -------------------------------- ### Stopping Pulse Job Processing and Graceful Shutdown in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-job-processor/stop.md This snippet demonstrates how to use the `pulse.stop()` method to halt job processing and unlock jobs. It also illustrates a robust graceful shutdown implementation for a Node.js application using `SIGTERM`, `SIGINT`, `unhandledRejection`, and `uncaughtException` events to ensure `pulse.stop()` is called before exiting, releasing any held jobs. ```TypeScript const pulse = new Pulse(); pulse.start(); async function graceful() { await pulse.stop(); process.exit(0); } process.on('SIGTERM', graceful); process.on('SIGINT' , graceful); process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); graceful(); }); process.on('uncaughtException', (error) => { console.error('Uncaught Exception thrown', error); graceful(); }); ``` -------------------------------- ### Checking Job Status with pulse.isRunning in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/isrunning.md This snippet demonstrates how to use the `isRunning` method within a Pulse job definition to check if the job is currently active. It logs a message indicating whether the job is running or not based on the method's return value. The `useRealStatus` parameter is not explicitly used here, so it defaults to `false`. ```TypeScript const pulse = new Pulse(); pulse.define('test', async (job) => { if (job.isRunning()) { console.log('The job is currently running.'); } else { console.log('The job is not running.'); } }); ``` -------------------------------- ### Disabling Jobs with Pulse in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/disable.md This snippet demonstrates how to use the `pulse.disable` method to selectively disable jobs based on a MongoDB query. It initializes a `Pulse` instance and then calls `disable` with a query to target jobs scheduled for weekends. The promise resolves with the count of modified jobs or catches an error, providing feedback on the operation's success. ```typescript const pulse = new Pulse(); // Example of disabling all jobs that are scheduled to run on weekends const weekendQuery = { runDay: { $in: ['Saturday', 'Sunday'] } }; pulse.disable(weekendQuery) .then(modifiedCount => console.log(`${modifiedCount} jobs scheduled for weekends were disabled`)) .catch(error => console.error('Failed to disable jobs:', error)); ``` -------------------------------- ### Disabling and Saving a Job in PulseCron (TypeScript) Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/manually-working/repeatevery-9.md This snippet demonstrates how to disable a job using the `job.disable()` method in PulseCron. It shows creating a new job, disabling it, and then explicitly saving the job's new disabled status to the database. The `disable()` method prevents the job from being run, and `save()` persists this change, as `disable()` itself does not save the job state. ```typescript const job = pulse.create('test', {}); job.disable(); job.save(); // If you want to save it ``` -------------------------------- ### Checking Job Lock Expiration with Pulse in TypeScript Source: https://github.com/pulsecron/pulse/blob/main/gitbook/docs/managing-jobs/isexpired.md This snippet demonstrates how to use the `isExpired` method within a Pulse job definition. It checks if the current job's lock has expired and logs a corresponding message. This method is crucial for handling stalled or failed jobs that haven't been updated within their expected lock lifetime. ```TypeScript const pulse = new Pulse(); pulse.define('test', async (job) => { if (job.isExpired()) { console.log('The job lock has expired.'); } else { console.log('The job lock is still valid.'); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.