Socket
Socket
Sign inDemoInstall

@tngtech/momo-scheduler

Package Overview
Dependencies
34
Maintainers
6
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.0 to 1.1.0

3

CHANGELOG.md

@@ -6,3 +6,4 @@ # Change Log

## Next release
## v1.1.0 (2022-09-29)
- Feature: jobs can receive parameters ([#405](https://github.com/TNG/momo-scheduler/issues/405))

@@ -9,0 +10,0 @@ ## v1.0.0 (2022-07-11)

import { JobResult } from '../job/ExecutionInfo';
import { ExecutionsRepository } from '../repository/ExecutionsRepository';
import { Handler } from '../job/MomoJob';
import { Handler, JobParameters } from '../job/MomoJob';
import { JobEntity } from '../repository/JobEntity';

@@ -16,4 +16,4 @@ import { JobRepository } from '../repository/JobRepository';

stop(): void;
execute(jobEntity: JobEntity): Promise<JobResult>;
execute(jobEntity: JobEntity, parameters?: JobParameters): Promise<JobResult>;
private executeHandler;
}

@@ -20,3 +20,3 @@ "use strict";

}
execute(jobEntity) {
execute(jobEntity, parameters) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -33,3 +33,3 @@ const { added, running } = yield this.executionsRepository.addExecution(this.scheduleId, jobEntity.name, jobEntity.maxRunning);

}
const { started, result } = yield this.executeHandler(jobEntity);
const { started, result } = yield this.executeHandler(jobEntity, parameters);
yield this.jobRepository.updateJob(jobEntity.name, {

@@ -53,3 +53,3 @@ executionInfo: {

}
executeHandler(jobEntity) {
executeHandler(jobEntity, parameters) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -60,3 +60,3 @@ this.logger.debug('run job', { name: jobEntity.name });

try {
const data = yield this.handler();
const data = yield this.handler(parameters);
result = {

@@ -63,0 +63,0 @@ status: ExecutionInfo_1.ExecutionStatus.finished,

@@ -5,3 +5,3 @@ export { MomoOptions, MongoSchedule } from './schedule/MongoSchedule';

export { MomoEvent, MomoErrorEvent, MomoEventData } from './logging/MomoEvents';
export { MomoJob } from './job/MomoJob';
export { MomoJob, JobParameters } from './job/MomoJob';
export { MomoJobDescription, JobSchedulerStatus } from './job/MomoJobDescription';

@@ -8,0 +8,0 @@ export { ExecutionStatus } from './job/ExecutionInfo';

import { Result } from 'neverthrow';
import { CronSchedule, Handler, IntervalSchedule, MomoJob, TypedMomoJob } from './MomoJob';
import { CronSchedule, Handler, IntervalSchedule, JobParameters, MomoJob, TypedMomoJob } from './MomoJob';
export interface ParsedIntervalSchedule extends Required<IntervalSchedule> {

@@ -12,2 +12,3 @@ parsedInterval: number;

maxRunning: number;
parameters?: JobParameters;
}

@@ -40,2 +41,2 @@ export interface Job<Schedule = ParsedIntervalSchedule | CronSchedule> extends JobDefinition<Schedule> {

*/
export declare function toJobDefinition<Schedule extends ParsedIntervalSchedule | CronSchedule, Type extends JobDefinition<Schedule>>({ name, schedule, maxRunning, concurrency }: Type): JobDefinition<Schedule>;
export declare function toJobDefinition<Schedule extends ParsedIntervalSchedule | CronSchedule, Type extends JobDefinition<Schedule>>({ name, schedule, maxRunning, concurrency, parameters }: Type): JobDefinition<Schedule>;

@@ -81,6 +81,6 @@ "use strict";

*/
function toJobDefinition({ name, schedule, maxRunning, concurrency }) {
return { name, schedule, maxRunning, concurrency };
function toJobDefinition({ name, schedule, maxRunning, concurrency, parameters }) {
return { name, schedule, maxRunning, concurrency, parameters };
}
exports.toJobDefinition = toJobDefinition;
//# sourceMappingURL=Job.js.map
import { ParsedIntervalSchedule } from './Job';
export declare type Handler = () => Promise<string | undefined | void> | string | undefined | void;
export declare type JobParameters = Record<string, object | number | string | boolean | undefined>;
export declare type Handler = (parameters?: JobParameters) => Promise<string | undefined | void> | string | undefined | void;
export interface TypedMomoJob<Schedule> {

@@ -9,2 +10,3 @@ handler: Handler;

maxRunning?: number;
parameters?: JobParameters;
}

@@ -11,0 +13,0 @@ export declare type MomoJob = TypedMomoJob<IntervalSchedule> | TypedMomoJob<CronSchedule>;

@@ -1,2 +0,2 @@

import { Handler, MomoJob } from './MomoJob';
import { Handler, JobParameters, MomoJob } from './MomoJob';
interface MomoJobBuilderBase<T> {

@@ -7,2 +7,3 @@ withName: (name: string) => T;

withHandler: (handler: Handler) => T;
withParameters: (parameters: JobParameters) => T;
build: () => MomoJob;

@@ -21,2 +22,3 @@ }

withCronSchedule(cronSchedule: string): MomoCronJobBuilder;
withParameters(jobParameters: JobParameters): this;
withConcurrency(concurrency: number): this;

@@ -23,0 +25,0 @@ withMaxRunning(maxRunning: number): this;

@@ -20,2 +20,6 @@ "use strict";

}
withParameters(jobParameters) {
this.momoJob.parameters = jobParameters;
return this;
}
withConcurrency(concurrency) {

@@ -22,0 +26,0 @@ this.momoJob.concurrency = concurrency;

import { JobEntity } from '../repository/JobEntity';
import { CronSchedule, IntervalSchedule } from './MomoJob';
import { CronSchedule, IntervalSchedule, JobParameters } from './MomoJob';
/**

@@ -18,5 +18,6 @@ * information about scheduled job

maxRunning: number;
parameters?: JobParameters;
/** present only if the job is started */
schedulerStatus?: JobSchedulerStatus;
}
export declare function toMomoJobDescription({ name, schedule, concurrency, maxRunning }: JobEntity): MomoJobDescription;
export declare function toMomoJobDescription({ name, schedule, concurrency, maxRunning, parameters, }: JobEntity): MomoJobDescription;

@@ -5,3 +5,3 @@ "use strict";

const MomoJob_1 = require("./MomoJob");
function toMomoJobDescription({ name, schedule, concurrency, maxRunning }) {
function toMomoJobDescription({ name, schedule, concurrency, maxRunning, parameters, }) {
return {

@@ -12,2 +12,3 @@ name,

maxRunning,
parameters,
};

@@ -14,0 +15,0 @@ }

@@ -5,3 +5,3 @@ import { ExecutionInfo, JobResult } from '../job/ExecutionInfo';

import { LogEmitter } from '../logging/LogEmitter';
import { MomoJob } from '../job/MomoJob';
import { JobParameters, MomoJob } from '../job/MomoJob';
import { MomoJobDescription } from '../job/MomoJobDescription';

@@ -50,6 +50,7 @@ export declare class Schedule extends LogEmitter {

* @param name the job to run
* @param parameters the parameters that will be passed to the job for this single run; passing nothing will run the job with no parameters, regardless of potentially set job parameters for the scheduled runs
* @param delay the job will be run after delay milliseconds
* @returns the return value of the job's handler or one of: 'finished', 'max running reached' (job could not be executed), 'not found', 'failed'
*/
run(name: string, delay?: number): Promise<JobResult>;
run(name: string, parameters?: JobParameters, delay?: number): Promise<JobResult>;
/**

@@ -56,0 +57,0 @@ * Schedule all defined jobs.

@@ -57,4 +57,4 @@ "use strict";

if (jobResult.isErr()) {
const { handler, schedule } = momoJob, data = tslib_1.__rest(momoJob, ["handler", "schedule"]);
this.logger.error('job cannot be defined', MomoErrorType_1.MomoErrorType.defineJob, Object.assign(Object.assign({}, data), schedule), jobResult.error);
const { schedule, name, maxRunning } = momoJob;
this.logger.error('job cannot be defined', MomoErrorType_1.MomoErrorType.defineJob, Object.assign({ name, maxRunning }, schedule), jobResult.error);
return false;

@@ -77,6 +77,7 @@ }

* @param name the job to run
* @param parameters the parameters that will be passed to the job for this single run; passing nothing will run the job with no parameters, regardless of potentially set job parameters for the scheduled runs
* @param delay the job will be run after delay milliseconds
* @returns the return value of the job's handler or one of: 'finished', 'max running reached' (job could not be executed), 'not found', 'failed'
*/
run(name, delay = 0) {
run(name, parameters, delay = 0) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -89,3 +90,3 @@ const jobScheduler = this.jobSchedulers[name];

if (delay <= 0) {
return jobScheduler.executeOnce();
return jobScheduler.executeOnce(parameters);
}

@@ -92,0 +93,0 @@ return new Promise((resolve) => (0, safeTimeouts_1.setSafeTimeout)(() => tslib_1.__awaiter(this, void 0, void 0, function* () { return resolve(yield jobScheduler.executeOnce()); }), delay, this.logger, 'Single execution failed'));

import { CronSchedule } from '../job/MomoJob';
import { ExecutableSchedule, NextExecutionTime } from './ExecutableSchedule';
import { Logger } from '../logging/Logger';
import { ExecutableSchedule, ExecutionParameters, NextExecutionTime } from './ExecutableSchedule';
export declare class ExecutableCronSchedule implements ExecutableSchedule<CronSchedule> {

@@ -9,3 +8,3 @@ private readonly cronSchedule;

toObject(): CronSchedule;
execute(callback: () => Promise<void>, logger: Logger, errorMessage: string): NextExecutionTime;
execute({ callback, jobParameters, logger, errorMessage }: ExecutionParameters): NextExecutionTime;
stop(): void;

@@ -12,0 +11,0 @@ isStarted(): boolean;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExecutableCronSchedule = void 0;
const tslib_1 = require("tslib");
const cron_parser_1 = require("cron-parser");

@@ -16,5 +17,5 @@ const cron_1 = require("cron");

}
execute(callback, logger, errorMessage) {
execute({ callback, jobParameters, logger, errorMessage }) {
this.validateCronSchedule();
this.scheduledJob = new cron_1.CronJob(this.cronSchedule, callback);
this.scheduledJob = new cron_1.CronJob(this.cronSchedule, () => tslib_1.__awaiter(this, void 0, void 0, function* () { return callback(jobParameters); }));
try {

@@ -21,0 +22,0 @@ this.scheduledJob.start();

@@ -1,4 +0,2 @@

import { Logger } from '../logging/Logger';
import { ExecutableSchedule, NextExecutionTime } from './ExecutableSchedule';
import { ExecutionInfo } from '../job/ExecutionInfo';
import { ExecutableSchedule, ExecutionParameters, NextExecutionTime } from './ExecutableSchedule';
import { ParsedIntervalSchedule } from '../job/Job';

@@ -14,3 +12,3 @@ import { IntervalSchedule } from '../job/MomoJob';

toObject(): Required<IntervalSchedule>;
execute(callback: () => Promise<void>, logger: Logger, errorMessage: string, executionInfo?: ExecutionInfo): NextExecutionTime;
execute({ executionInfo, callback, jobParameters, logger, errorMessage }: ExecutionParameters): NextExecutionTime;
isStarted(): boolean;

@@ -17,0 +15,0 @@ stop(): void;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExecutableIntervalSchedule = void 0;
const tslib_1 = require("tslib");
const lodash_1 = require("lodash");

@@ -20,5 +21,5 @@ const luxon_1 = require("luxon");

}
execute(callback, logger, errorMessage, executionInfo) {
execute({ executionInfo, callback, jobParameters, logger, errorMessage }) {
const delay = this.calculateDelay(executionInfo);
this.timeoutHandle = (0, setSafeIntervalWithDelay_1.setSafeIntervalWithDelay)(callback, this.parsedInterval, delay, logger, errorMessage);
this.timeoutHandle = (0, setSafeIntervalWithDelay_1.setSafeIntervalWithDelay)(() => tslib_1.__awaiter(this, void 0, void 0, function* () { return callback(jobParameters); }), this.parsedInterval, delay, logger, errorMessage);
return { nextExecution: luxon_1.DateTime.fromMillis(luxon_1.DateTime.now().toMillis() + delay) };

@@ -25,0 +26,0 @@ }

import { DateTime } from 'luxon';
import { Logger } from '../logging/Logger';
import { CronSchedule } from '../job/MomoJob';
import { CronSchedule, JobParameters } from '../job/MomoJob';
import { ExecutableIntervalSchedule } from './ExecutableIntervalSchedule';

@@ -11,4 +11,11 @@ import { ExecutableCronSchedule } from './ExecutableCronSchedule';

}
export interface ExecutionParameters {
callback: (parameters?: JobParameters) => Promise<void>;
logger: Logger;
errorMessage: string;
jobParameters?: JobParameters;
executionInfo?: ExecutionInfo;
}
export interface ExecutableSchedule<I> {
execute: (callback: () => Promise<void>, logger: Logger, errorMessage: string, executionInfo?: ExecutionInfo) => NextExecutionTime;
execute: (executionParameters: ExecutionParameters) => NextExecutionTime;
stop: () => void;

@@ -15,0 +22,0 @@ isStarted: () => boolean;

@@ -8,2 +8,3 @@ import { JobResult } from '../job/ExecutionInfo';

import { MomoJobDescription } from '../job/MomoJobDescription';
import { JobParameters } from '../job/MomoJob';
export declare class JobScheduler {

@@ -25,5 +26,5 @@ private readonly jobName;

stop(): Promise<void>;
executeOnce(): Promise<JobResult>;
executeConcurrently(): Promise<void>;
executeOnce(parameters?: JobParameters): Promise<JobResult>;
executeConcurrently(parameters?: JobParameters): Promise<void>;
private handleUnexpectedError;
}

@@ -58,3 +58,9 @@ "use strict";

this.executableSchedule = (0, ExecutableSchedule_1.toExecutableSchedule)(jobEntity.schedule);
const { nextExecution } = this.executableSchedule.execute(this.executeConcurrently.bind(this), this.logger, 'Concurrent execution failed', jobEntity.executionInfo);
const { nextExecution } = this.executableSchedule.execute({
callback: this.executeConcurrently.bind(this),
logger: this.logger,
errorMessage: 'Concurrent execution failed',
jobParameters: jobEntity.parameters,
executionInfo: jobEntity.executionInfo,
});
this.logger.debug(`scheduled job to run at ${nextExecution}`, Object.assign({ name: this.jobName }, this.executableSchedule.toObject()));

@@ -73,3 +79,3 @@ });

}
executeOnce() {
executeOnce(parameters) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -84,3 +90,3 @@ try {

}
return this.jobExecutor.execute(jobEntity);
return this.jobExecutor.execute(jobEntity, parameters);
}

@@ -95,3 +101,3 @@ catch (e) {

}
executeConcurrently() {
executeConcurrently(parameters) {
var _a;

@@ -112,3 +118,3 @@ return tslib_1.__awaiter(this, void 0, void 0, function* () {

// eslint-disable-next-line no-void
void this.jobExecutor.execute(jobEntity).catch((e) => {
void this.jobExecutor.execute(jobEntity, parameters).catch((e) => {
this.handleUnexpectedError(e);

@@ -115,0 +121,0 @@ });

{
"name": "@tngtech/momo-scheduler",
"version": "1.0.0",
"version": "1.1.0",
"description": "momo is a scheduler that persists jobs in mongodb",

@@ -33,11 +33,11 @@ "main": "dist/index.js",

"dependencies": {
"cron": "2.0.0",
"cron-parser": "4.5.0",
"cron": "2.1.0",
"cron-parser": "4.6.0",
"human-interval": "2.0.1",
"lodash": "4.17.21",
"luxon": "3.0.1",
"mongodb": "4.7.0",
"neverthrow": "4.4.2",
"luxon": "3.0.4",
"mongodb": "4.10.0",
"neverthrow": "5.0.0",
"typed-emitter": "2.1.0",
"uuid": "8.3.2"
"uuid": "9.0.0"
},

@@ -48,28 +48,28 @@ "devDependencies": {

"@types/human-interval": "1.0.0",
"@types/jest": "28.1.4",
"@types/lodash": "4.14.182",
"@types/luxon": "2.3.2",
"@types/node": "16.11.43",
"@types/jest": "28.1.8",
"@types/lodash": "4.14.186",
"@types/luxon": "3.0.1",
"@types/node": "16.11.62",
"@types/pino": "7.0.4",
"@types/sinonjs__fake-timers": "8.1.2",
"@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.30.5",
"@typescript-eslint/parser": "5.30.5",
"eslint": "8.19.0",
"@typescript-eslint/eslint-plugin": "5.38.1",
"@typescript-eslint/parser": "5.38.1",
"eslint": "8.23.1",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jest": "26.5.3",
"eslint-plugin-jsdoc": "39.3.3",
"eslint-plugin-markdown": "2.2.1",
"eslint-plugin-jest": "27.0.4",
"eslint-plugin-jsdoc": "39.3.6",
"eslint-plugin-markdown": "3.0.0",
"eslint-plugin-prefer-arrow": "1.2.3",
"eslint-plugin-prettier": "4.2.1",
"jest": "28.1.2",
"mongodb-memory-server": "8.7.2",
"pino": "8.1.0",
"jest": "28.1.3",
"mongodb-memory-server": "8.9.3",
"pino": "8.6.1",
"prettier": "2.7.1",
"ts-jest": "28.0.5",
"ts-jest": "28.0.8",
"ts-mockito": "2.6.1",
"ts-node": "10.8.2",
"typescript": "4.7.4"
"ts-node": "10.9.1",
"typescript": "4.8.4"
}
}

@@ -39,2 +39,13 @@ # momo-scheduler <img src="momo_logo.svg" align="right" />

const mongo = await MongoMemoryServer.create();
const mongoSchedule = new MongoScheduleBuilder()
.withConnection({
url: await mongo.getUri(),
collectionsPrefix: 'momo',
pingInterval: 1000,
})
.withJob(intervalJob)
.withJob(cronJob)
.build();
const intervalJob: MomoJob = new MomoJobBuilder()

@@ -45,23 +56,25 @@ .withName('interval job')

.withSchedule('5 seconds')
.withParameters({foo: 'bar'})
.withHandler(() => logger.error('This is a momo job that runs once every five seconds!'))
.build();
mongoSchedule.define(intervalJob);
const cronJob: MomoJob = new MomoJobBuilder()
.withName('interval job')
.withName('cron job')
.withConcurrency(1)
.withMaxRunning(1)
.withCronSchedule('0 0 * * 1-5')
.withParameters({foo: {bar: "baz"}})
.withHandler(() => logger.error('This is a momo job that runs every weekday at midnight!'))
.build();
mongoSchedule.define(cronJob);
const mongo = await MongoMemoryServer.create();
const mongoSchedule = new MongoScheduleBuilder()
.withConnection({
url: await mongo.getUri(),
collectionsPrefix: 'momo',
pingInterval: 1000,
})
.withJob(intervalJob)
.withJob(cronJob)
const cronJobWithNoParameters: MomoJob = new MomoJobBuilder()
.withName('cron job without parameters')
.withConcurrency(2)
.withMaxRunning(3)
.withCronSchedule('0 0 * * 1-3')
.withHandler(() => logger.error('This is a momo job that runs on Monday, Tuesday and Wednesday!'))
.build();
mongoSchedule.define(cronJobWithNoParameters);

@@ -87,10 +100,11 @@ // optional: listen to error and debug events

| setter | parameters | mandatory | default value | description |
| ---------------- |--------------------------------------------| --------- | ------------- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| withName | `string` | true | | The name of the job. Used as a unique identifier. |
| setter | parameters | mandatory | default value | description |
|------------------|----------------------------------------------------------|-----------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| withName | `string` | true | | The name of the job. Used as a unique identifier. |
| withSchedule | `number` or `string`,`number` or `string` (default: `0`) | false | | Either this setter or `withCronSchedule()` must be called. Specifies the schedule for starting the job. Time intervals can be given in human-readable formats (like '1 minute', 'ten days' or 'twenty-one days and 2 hours' ) or in milliseconds. Check the documentation of [ human-interval ](https://www.npmjs.com/package/human-interval) for details. If the job never ran before, the job will run after `firstRunAfter` for the first time. Just like the `interval`, `firstRunAfter` can also be given in a human-readable format or as milliseconds. |
| withCronSchedule | `string` | false | | Either this setter or `withCronSchedule()` must be called. Specifies the cron schedule according to which the job will run. |
| withConcurrency | `number` | false | 1 | How many instances of a job are started at a time. |
| withMaxRunning | `number` | false | 0 | Maximum number of job executions that is allowed at a time. Set to 0 for no max. The schedule will trigger no more job executions if maxRunning is reached. However, there is no guarantee that the schedule always respects the limit; in rare cases with multiple Momo instances maxRunning may be exceeded. |
| withHandler | `function` | true | | The function to execute. |
| withCronSchedule | `string` | false | | Either this setter or `withCronSchedule()` must be called. Specifies the cron schedule according to which the job will run. |
| withConcurrency | `number` | false | 1 | How many instances of a job are started at a time. |
| withMaxRunning | `number` | false | 0 | Maximum number of job executions that is allowed at a time. Set to 0 for no max. The schedule will trigger no more job executions if maxRunning is reached. However, there is no guarantee that the schedule always respects the limit; in rare cases with multiple Momo instances maxRunning may be exceeded. |
| withHandler | `function` | true | | The function to execute. |
| withParameters | `JobParameters` | false | | The parameters with which the function provided by `withHandler` is called. |

@@ -102,6 +116,6 @@ ### MongoSchedule

| setter | parameters | mandatory | default value | description |
| -------------- | ------------- | --------- | ------------- | --------------------------------------- |
| withJob | `MomoJob` | true | | Adds a job to the schedule. |
| withConnection | `MomoOptions` | true | | The connection options of the schedule. |
| setter | parameters | mandatory | default value | description |
|----------------|------------------------|-----------|---------------|-----------------------------------------|
| withJob | `job: MomoJob` | true | | Adds a job to the schedule. |
| withConnection | `options: MomoOptions` | true | | The connection options of the schedule. |

@@ -113,21 +127,21 @@ The start/stop/cancel/remove methods can take a job's name as an optional parameter.

| function | parameters | description |
| --------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| connect | `MomoConnectionOptions` | Creates a new MongoSchedule connected to your database. See below for the available options. |
| define | `MomoJob` | Creates a new MomoJob on the schedule. |
| start | | Starts jobs that are on the schedule. |
| stop | | Stops jobs, but does not remove them from either the schedule or the database. |
| cancel | | Stops and removes jobs from the schedule, does not remove them from the database. |
| remove | | Stops and removes jobs from both the schedule and the database. |
| startJob | `string` | Starts the job with the provided name (if on the schedule). |
| stopJob | `string` | Stops the job with the provided name (if on the schedule), but does not remove it from either the schedule or the database. |
| cancelJob | `string` | Stops and removes the job with the provided name (if on the schedule) from the schedule, does not remove it from the database. |
| removeJob | `string` | Stops and removes the job with the provided name (if on the schedule) from both the schedule and the database. |
| count | `boolean` (optional) | Returns the number of jobs on the schedule. Only started jobs are counted if parameter is set to true. |
| list | | Returns descriptions of all jobs on the schedule. |
| check | `string` | Returns execution information of the job with the provided name from the database. This also works if the job is not on the schedule. |
| clear | | Removes all jobs from the database. This also removes jobs that are not on this schedule, but were defined by other schedules. However, does NOT stop job executions - this will cause currently running jobs to fail. Consider using stop/cancel/remove methods instead! |
| get | `string` | Returns a description of the job. Returns undefined if no job with the provided name is defined. |
| run | `string`, `number` (default: `0`) | Runs the job with the provided name once, independently from the schedule, after the specified delay. Note that `maxRunning` is respected, ie. the execution is skipped if the job is already running `maxRunning` times. |
| on | `'debug'` or `'error'`, `function` | Define a callback for debug or error events. |
| function | parameters | description |
|-----------|------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| connect | `options: MomoConnectionOptions` | Creates a new MongoSchedule connected to your database. See below for the available options. |
| define | `job: MomoJob` | Creates a new MomoJob on the schedule. |
| start | | Starts jobs that are on the schedule. |
| stop | | Stops jobs, but does not remove them from either the schedule or the database. |
| cancel | | Stops and removes jobs from the schedule, does not remove them from the database. |
| remove | | Stops and removes jobs from both the schedule and the database. |
| startJob | `name: string` | Starts the job with the provided name (if on the schedule). |
| stopJob | `name: string` | Stops the job with the provided name (if on the schedule), but does not remove it from either the schedule or the database. |
| cancelJob | `name: string` | Stops and removes the job with the provided name (if on the schedule) from the schedule, does not remove it from the database. |
| removeJob | `name: string` | Stops and removes the job with the provided name (if on the schedule) from both the schedule and the database. |
| count | `onlyStarted: boolean` (optional) | Returns the number of jobs on the schedule. Only started jobs are counted if parameter is set to true. |
| list | | Returns descriptions of all jobs on the schedule. |
| check | `name: string` | Returns execution information of the job with the provided name from the database. This also works if the job is not on the schedule. |
| clear | | Removes all jobs from the database. This also removes jobs that are not on this schedule, but were defined by other schedules. However, does NOT stop job executions - this will cause currently running jobs to fail. Consider using stop/cancel/remove methods instead! |
| get | `name: string` | Returns a description of the job. Returns undefined if no job with the provided name is defined. |
| run | `name: string`, `parameters: JobParameters` (default: `undefined`), `delay: number` (default: `0`) | Runs the job with the provided name once, independently from the schedule, after the specified delay. If no parameters are provided, the job will be called with no parameters. Note that `maxRunning` is respected, ie. the execution is skipped if the job is already running `maxRunning` times. |
| on | `'debug'` or `'error'`, `function` | Define a callback for debug or error events. |

@@ -137,3 +151,3 @@ #### MomoConnectionOptions

| property | type | optional | default | description |
| ----------------- | -------- | -------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|-------------------|----------|----------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| url | `string` | false | | The connection string of your database. |

@@ -148,3 +162,3 @@ | collectionsPrefix | `string` | true | no prefix | A prefix for all collections created by Momo. |

| property | type | optional | description |
| --------------- | --------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|-----------------|-----------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| name | `string` | false | The name of the job. Used as a unique identifier. |

@@ -172,3 +186,3 @@ | interval | `string` | false | Specifies the time interval at which the job is started. |

| event | property | type | description |
| ----- | ---------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
|-------|------------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| both | message | `string` | Some information about the event that occurred. |

@@ -184,21 +198,25 @@ | both | data (optional) | `{ name?: string; ... }` | Contains additional information like the name of the affected job. |

const example1: MomoJob = new MomoJobBuilder()
const example1 = new MomoJobBuilder()
.withName('example 1')
.withInterval('5 minutes')
.withHandler(() => console.log('This is momo'));
.withHandler(() => console.log('This is momo'))
.build();
const example2: MomoJob = new MomoJobBuilder()
const example2 = new MomoJobBuilder()
.withName('example 2')
.withInterval('5 minutes', 60 * 1000) // first run after one minute
.withHandler(() => console.log('This is momo'));
.withHandler(() => console.log('This is momo'))
.build();
const example3: MomoJob = new MomoJobBuilder()
const example3 = new MomoJobBuilder()
.withName('example 3')
.withInterval('5 minutes', '4 minutes') // first run after four minutes
.withHandler(() => console.log('This is momo'));
.withHandler(() => console.log('This is momo'))
.build();
const example4: MomoJob = new MomoJobBuilder()
const example4 = new MomoJobBuilder()
.withName('example 4')
.withCronSchedule('0 0 * * 1-5') // every weekday at midnight
.withHandler(() => console.log('This is momo'));
.withHandler(() => console.log('This is momo'))
.build();
```

@@ -205,0 +223,0 @@

@@ -5,3 +5,3 @@ import { DateTime } from 'luxon';

import { ExecutionsRepository } from '../repository/ExecutionsRepository';
import { Handler } from '../job/MomoJob';
import { Handler, JobParameters } from '../job/MomoJob';
import { JobEntity } from '../repository/JobEntity';

@@ -27,3 +27,3 @@ import { JobRepository } from '../repository/JobRepository';

async execute(jobEntity: JobEntity): Promise<JobResult> {
async execute(jobEntity: JobEntity, parameters?: JobParameters): Promise<JobResult> {
const { added, running } = await this.executionsRepository.addExecution(

@@ -44,3 +44,3 @@ this.scheduleId,

const { started, result } = await this.executeHandler(jobEntity);
const { started, result } = await this.executeHandler(jobEntity, parameters);

@@ -68,3 +68,6 @@ await this.jobRepository.updateJob(jobEntity.name, {

private async executeHandler(jobEntity: JobEntity): Promise<{ started: DateTime; result: JobResult }> {
private async executeHandler(
jobEntity: JobEntity,
parameters?: JobParameters
): Promise<{ started: DateTime; result: JobResult }> {
this.logger.debug('run job', { name: jobEntity.name });

@@ -75,3 +78,3 @@ const started = DateTime.now();

try {
const data = await this.handler();
const data = await this.handler(parameters);
result = {

@@ -78,0 +81,0 @@ status: ExecutionStatus.finished,

@@ -5,3 +5,3 @@ export { MomoOptions, MongoSchedule } from './schedule/MongoSchedule';

export { MomoEvent, MomoErrorEvent, MomoEventData } from './logging/MomoEvents';
export { MomoJob } from './job/MomoJob';
export { MomoJob, JobParameters } from './job/MomoJob';
export { MomoJobDescription, JobSchedulerStatus } from './job/MomoJobDescription';

@@ -8,0 +8,0 @@ export { ExecutionStatus } from './job/ExecutionInfo';

@@ -5,3 +5,3 @@ import humanInterval from 'human-interval';

import { CronSchedule, Handler, IntervalSchedule, MomoJob, TypedMomoJob, isCronJob } from './MomoJob';
import { CronSchedule, Handler, IntervalSchedule, JobParameters, MomoJob, TypedMomoJob, isCronJob } from './MomoJob';
import { momoError } from '../logging/error/MomoError';

@@ -19,2 +19,3 @@

maxRunning: number;
parameters?: JobParameters;
}

@@ -110,4 +111,4 @@

Type extends JobDefinition<Schedule>
>({ name, schedule, maxRunning, concurrency }: Type): JobDefinition<Schedule> {
return { name, schedule, maxRunning, concurrency };
>({ name, schedule, maxRunning, concurrency, parameters }: Type): JobDefinition<Schedule> {
return { name, schedule, maxRunning, concurrency, parameters };
}
import { ParsedIntervalSchedule } from './Job';
export type Handler = () => Promise<string | undefined | void> | string | undefined | void;
export type JobParameters = Record<string, object | number | string | boolean | undefined>;
export type Handler = (parameters?: JobParameters) => Promise<string | undefined | void> | string | undefined | void;
export interface TypedMomoJob<Schedule> {

@@ -11,2 +13,3 @@ handler: Handler;

maxRunning?: number;
parameters?: JobParameters;
}

@@ -13,0 +16,0 @@

@@ -1,2 +0,2 @@

import { Handler, MomoJob } from './MomoJob';
import { Handler, JobParameters, MomoJob } from './MomoJob';

@@ -8,2 +8,3 @@ interface MomoJobBuilderBase<T> {

withHandler: (handler: Handler) => T;
withParameters: (parameters: JobParameters) => T;
build: () => MomoJob;

@@ -38,2 +39,7 @@ }

withParameters(jobParameters: JobParameters): this {
this.momoJob.parameters = jobParameters;
return this;
}
withConcurrency(concurrency: number): this {

@@ -40,0 +46,0 @@ this.momoJob.concurrency = concurrency;

import { JobEntity } from '../repository/JobEntity';
import { CronSchedule, IntervalSchedule, toSchedule } from './MomoJob';
import { CronSchedule, IntervalSchedule, JobParameters, toSchedule } from './MomoJob';

@@ -20,2 +20,3 @@ /**

maxRunning: number;
parameters?: JobParameters;
/** present only if the job is started */

@@ -25,3 +26,9 @@ schedulerStatus?: JobSchedulerStatus;

export function toMomoJobDescription({ name, schedule, concurrency, maxRunning }: JobEntity): MomoJobDescription {
export function toMomoJobDescription({
name,
schedule,
concurrency,
maxRunning,
parameters,
}: JobEntity): MomoJobDescription {
return {

@@ -32,3 +39,4 @@ name,

maxRunning,
parameters,
};
}

@@ -9,3 +9,3 @@ import { sum } from 'lodash';

import { MomoErrorType } from '../logging/error/MomoErrorType';
import { MomoJob } from '../job/MomoJob';
import { JobParameters, MomoJob } from '../job/MomoJob';
import { MomoJobDescription } from '../job/MomoJobDescription';

@@ -62,4 +62,9 @@ import { tryToJob } from '../job/Job';

if (jobResult.isErr()) {
const { handler, schedule, ...data } = momoJob;
this.logger.error('job cannot be defined', MomoErrorType.defineJob, { ...data, ...schedule }, jobResult.error);
const { schedule, name, maxRunning } = momoJob;
this.logger.error(
'job cannot be defined',
MomoErrorType.defineJob,
{ name, maxRunning, ...schedule },
jobResult.error
);
return false;

@@ -92,6 +97,7 @@ }

* @param name the job to run
* @param parameters the parameters that will be passed to the job for this single run; passing nothing will run the job with no parameters, regardless of potentially set job parameters for the scheduled runs
* @param delay the job will be run after delay milliseconds
* @returns the return value of the job's handler or one of: 'finished', 'max running reached' (job could not be executed), 'not found', 'failed'
*/
public async run(name: string, delay = 0): Promise<JobResult> {
public async run(name: string, parameters?: JobParameters, delay = 0): Promise<JobResult> {
const jobScheduler = this.jobSchedulers[name];

@@ -105,3 +111,3 @@

if (delay <= 0) {
return jobScheduler.executeOnce();
return jobScheduler.executeOnce(parameters);
}

@@ -108,0 +114,0 @@

@@ -6,6 +6,5 @@ import { parseExpression } from 'cron-parser';

import { CronSchedule } from '../job/MomoJob';
import { ExecutableSchedule, NextExecutionTime } from './ExecutableSchedule';
import { ExecutableSchedule, ExecutionParameters, NextExecutionTime } from './ExecutableSchedule';
import { momoError } from '../logging/error/MomoError';
import { MomoErrorType } from '../logging/error/MomoErrorType';
import { Logger } from '../logging/Logger';

@@ -24,6 +23,6 @@ export class ExecutableCronSchedule implements ExecutableSchedule<CronSchedule> {

execute(callback: () => Promise<void>, logger: Logger, errorMessage: string): NextExecutionTime {
execute({ callback, jobParameters, logger, errorMessage }: ExecutionParameters): NextExecutionTime {
this.validateCronSchedule();
this.scheduledJob = new CronJob(this.cronSchedule, callback);
this.scheduledJob = new CronJob(this.cronSchedule, async () => callback(jobParameters));
try {

@@ -30,0 +29,0 @@ this.scheduledJob.start();

@@ -5,4 +5,3 @@ import { max } from 'lodash';

import { TimeoutHandle, setSafeIntervalWithDelay } from '../timeout/setSafeIntervalWithDelay';
import { Logger } from '../logging/Logger';
import { ExecutableSchedule, NextExecutionTime } from './ExecutableSchedule';
import { ExecutableSchedule, ExecutionParameters, NextExecutionTime } from './ExecutableSchedule';
import { ExecutionInfo } from '../job/ExecutionInfo';

@@ -33,11 +32,12 @@ import { ParsedIntervalSchedule } from '../job/Job';

execute(
callback: () => Promise<void>,
logger: Logger,
errorMessage: string,
executionInfo?: ExecutionInfo
): NextExecutionTime {
execute({ executionInfo, callback, jobParameters, logger, errorMessage }: ExecutionParameters): NextExecutionTime {
const delay = this.calculateDelay(executionInfo);
this.timeoutHandle = setSafeIntervalWithDelay(callback, this.parsedInterval, delay, logger, errorMessage);
this.timeoutHandle = setSafeIntervalWithDelay(
async () => callback(jobParameters),
this.parsedInterval,
delay,
logger,
errorMessage
);

@@ -44,0 +44,0 @@ return { nextExecution: DateTime.fromMillis(DateTime.now().toMillis() + delay) };

import { DateTime } from 'luxon';
import { Logger } from '../logging/Logger';
import { CronSchedule, isCronSchedule } from '../job/MomoJob';
import { CronSchedule, JobParameters, isCronSchedule } from '../job/MomoJob';
import { ExecutableIntervalSchedule } from './ExecutableIntervalSchedule';

@@ -14,9 +14,12 @@ import { ExecutableCronSchedule } from './ExecutableCronSchedule';

export interface ExecutionParameters {
callback: (parameters?: JobParameters) => Promise<void>;
logger: Logger;
errorMessage: string;
jobParameters?: JobParameters;
executionInfo?: ExecutionInfo;
}
export interface ExecutableSchedule<I> {
execute: (
callback: () => Promise<void>,
logger: Logger,
errorMessage: string,
executionInfo?: ExecutionInfo
) => NextExecutionTime;
execute: (executionParameters: ExecutionParameters) => NextExecutionTime;
stop: () => void;

@@ -23,0 +26,0 @@ isStarted: () => boolean;

@@ -15,2 +15,3 @@ import { min } from 'lodash';

import { toExecutableSchedule } from './ExecutableSchedule';
import { JobParameters } from '../job/MomoJob';

@@ -87,8 +88,9 @@ export class JobScheduler {

const { nextExecution } = this.executableSchedule.execute(
this.executeConcurrently.bind(this),
this.logger,
'Concurrent execution failed',
jobEntity.executionInfo
);
const { nextExecution } = this.executableSchedule.execute({
callback: this.executeConcurrently.bind(this),
logger: this.logger,
errorMessage: 'Concurrent execution failed',
jobParameters: jobEntity.parameters,
executionInfo: jobEntity.executionInfo,
});

@@ -110,3 +112,3 @@ this.logger.debug(`scheduled job to run at ${nextExecution}`, {

async executeOnce(): Promise<JobResult> {
async executeOnce(parameters?: JobParameters): Promise<JobResult> {
try {

@@ -126,3 +128,3 @@ const jobEntity = await this.jobRepository.findOne({ name: this.jobName });

return this.jobExecutor.execute(jobEntity);
return this.jobExecutor.execute(jobEntity, parameters);
} catch (e) {

@@ -136,3 +138,3 @@ this.handleUnexpectedError(e);

async executeConcurrently(): Promise<void> {
async executeConcurrently(parameters?: JobParameters): Promise<void> {
try {

@@ -159,3 +161,3 @@ const jobEntity = await this.jobRepository.findOne({ name: this.jobName });

// eslint-disable-next-line no-void
void this.jobExecutor.execute(jobEntity).catch((e) => {
void this.jobExecutor.execute(jobEntity, parameters).catch((e) => {
this.handleUnexpectedError(e);

@@ -162,0 +164,0 @@ });

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc