npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

expressots-cron

v1.1.1

Published

Expressots - Cron Provider (expressots-cron)

Downloads

13

Readme

Expressots-cron

About

Expressots-cron package is a provider for Expressots that facilitates using cron jobs through a decorator and a cron provider. Expressots-cron is buit on top of cron package for Nodejs and it includes most of it's features. Check out blew sections for further details on how to use and API.

Table of Contents

Installation

Install the package via npm:

npm install expressots-cron

Usage

Make sure to register your provider inside your app.provider.ts

import { AppExpress } from "@expressots/adapter-express";
import {
    Env,
    IMiddleware,
    Middleware,
    provide,
    ProviderManager,
} from "@expressots/core";
import { container } from "../../app.container";
import { CronProvider } from "expressots-cron";

@provide(App)
export class App extends AppExpress {
    private middleware: IMiddleware;
    private provider: ProviderManager;

    constructor() {
        super();
        this.middleware = container.get<IMiddleware>(Middleware);
        this.provider = container.get(ProviderManager);
    }

    protected configureServices(): void {
        this.provider.register(Env);
        this.provider.register(CronProvider); // register here
    }

    protected postServerInitialization(): void {
        if (this.isDevelopment()) {
            this.provider.get(Env).checkAll();
        }
    }

    protected serverShutdown(): void {}
}

use it inside a controller file or a usecase.

using the decorator:

import { controller } from "@expressots/adapter-express";
import { AppUseCase } from "./app.usecase";
import { CronProvider, Cron } from "expressots-cron";
import { postConstruct } from "inversify";

@controller("/")
export class AppController {
    constructor(
        private appUseCase: AppUseCase,
        private cronProvider: CronProvider,
    ) {}

    @postConstruct() // must use postConstruct from inversify, if not the cron will not run automatically.
    init() {
        this.runCron();
    }

    @Cron("*/2 * * * * *", { name: "cronjob", timezone: "America/New_York" }) // if no name is assigned, a random uuid is generated
    public runCron() {
        console.log("cron running !");
        //
        const job = this.cronProvider.getTask("cronjob"); // retrieves a job by a provided name
        console.log(job); // typeof job is CronJob
    }
}

using the provider:

import { controller } from "@expressots/adapter-express";
import { AppUseCase } from "./app.usecase";
import { CronProvider, Cron } from "expressots-cron";
import { postConstruct } from "inversify";

@controller("/")
export class AppController {
    constructor(
        private appUseCase: AppUseCase,
        private cronProvider: CronProvider,
    ) {}

    @postConstruct()
    init() {
        this.runCron();
    }

    public runCron() {
        const job = this.cronProvider.schedule(
            "*/2 * * * * *",
            () => {
                console.log("cron running");
            },
            {
                name: "MyCronJob",
                startImmediately: false, // set to true to start the job immediately
            },
        );

        job.start();
    }
}

API

The cron package uses a simple and familiar cron syntax to define recurring tasks. The syntax consists of five fields:

* * * * *
| | | | |
| | | | └── Day of the week (0 - 7) (Sunday to Saturday)
| | | └──── Month (1 - 12)
| | └────── Day of the month (1 - 31)
| └──────── Hour (0 - 23)
└────────── Minute (0 - 59)

For example:

  • * * * * * – Run the task every minute.
  • 0 0 * * * – Run the task every day at midnight.

Cron Decorator

@Cron("*/2 * * * * *", options)

options are:

export interface ScheduleOptions {
  /**
   * The timezone that is used for job scheduling
   */
  timezone?: string;

  /**
   * Specifies whether to start the job immediately
   *
   * Defaults to `true`
   */

  startImmediately?: boolean;

  /**
   * The function to execute when the job completes
   * @returns void
   */

  onCompleted?: () => void;

  /**
   * The schedule name
   */
  name?: string;
}

Cron Provider

methods that are available on the provider:

export interface ICron {
  /**
   * Creates a new task to execute the given function when the cron expression ticks.
   * @param cronExpression
   * @param func
   * @param options
   */
  schedule(cronExpression: string, func: () => void, options?: ScheduleOptions): CronJob;

  /**
   * Get the list of tasks created using the `schedule` function
   */
  getTasks(): Map<string, CronJob>;

  /**
   * Get a specific task created using the `schedule` function
   * @param name
   */
  getTask(name: string): CronJob;
}

Methods

start: Initiates the job.

stop: Halts the job.

setTime: Modifies the time for the CronJob. Parameter must be a CronTime.

lastDate: Provides the last execution date.

nextDate: Indicates the subsequent date that will activate an onTick.

nextDates(count): Supplies an array of upcoming dates that will initiate an onTick.

fireOnTick: Allows modification of the onTick calling behavior.

addCallback: Permits addition of onTick callbacks.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author Lhon Rafaat Mohammed