# SilentCronX

[![npm version](https://img.shields.io/npm/v/silent-cronx.svg?color=0f766e)](https://www.npmjs.com/package/silent-cronx)
[![Node.js](https://img.shields.io/badge/node-%3E%3D18-339933.svg)](https://nodejs.org)
[![TypeScript](https://img.shields.io/badge/types-TypeScript-3178c6.svg)](https://www.typescriptlang.org)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Runtime deps](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen.svg)](package.json)

SilentCronX is a fully customized, TypeScript-first background job, queue, worker, cron, progress, and React/React Native compatible SDK for Node.js. It is built as original SDK code by **Pradeep Kumar Sheoran (Developer)** at **BSG Technologies** with no runtime third-party library dependency.

Official website: **https://bsgtechnologies.com**  
Visit here to meet, learn, contribute, and discuss new topics with us.

Contact / WhatsApp: **+91-8595147850**  
Donation / Support UPI mobile number: **+91-8595147850**  
Looking For a Job Change: You can use my Reactjs, React Native, Android (Java), Nodejs packages, and newly launched scripts including TypeScript. Any feature or update you want, leave a comment.

## Why SilentCronX

- Cron, delay, interval, immediate, queue, and worker-thread jobs from one SDK.
- Fully customizable job options: retry, timeout, priority, payload, logger, storage, concurrency, locks, and overlap prevention.
- Reliable execution model with graceful shutdown, `AbortSignal` cancellation, lifecycle events, event history, health snapshots, and job status tracking.
- Advanced queue operations: pause, resume, clear, inspect stats, set concurrency, use rate limits, and prioritize work.
- Native job progress updates for ReactJS and React Native progress bars.
- Built-in native `fetch` API client through `createSilentCronXClient`.
- Safe by design: no `eval`, no shell execution by default, no hidden process behavior, and serializable payload validation.
- React, React Native, Android, and web-app friendly through normal API routes: run jobs on Node.js, call them from any client.
- Modern Node.js and TypeScript output: ESM, CJS, and declaration files.
- Runtime dependency-free package code; dev tools are only used to build and typecheck the SDK.

## Installation

```bash
npm install silent-cronx
```

## Quickstart

```ts
import { createSilentCronX } from "silent-cronx";

const cron = createSilentCronX({
  timezone: "Asia/Kolkata",
  maxWorkers: 4,
  maxConcurrency: 25,
  defaultTimeout: 30_000,
  preventOverlapping: true,
  logger: console,
});

cron.on("job:success", (event) => {
  console.log("Job completed", event.name, event.durationMs);
});

await cron.schedule("daily-report", {
  cron: "0 9 * * *",
  payload: { reportType: "sales" },
  retry: { attempts: 3, backoff: "exponential", delayMs: 1000, maxDelayMs: 10_000, jitter: true },
  timeout: 20_000,
  preventOverlap: true,
  task: async ({ payload, signal, progress }) => {
    if (signal.aborted) return;
    await progress({ percent: 25, message: "Report started" });
    console.log("Generating report:", payload.reportType);
    await progress({ percent: 100, message: "Report completed" });
  },
});

cron.start();

process.once("SIGINT", async () => {
  await cron.shutdown();
  process.exit(0);
});
```

## Feature Examples

### Run a Job Immediately

```ts
const result = await cron.runNow("send-welcome", {
  payload: { userId: 101 },
  task: async ({ payload }) => {
    return { sent: true, userId: payload.userId };
  },
});

console.log(result.status, result.result);
```

### Delay a Job

```ts
await cron.delay("follow-up-message", {
  delayMs: 5_000,
  payload: { phone: "+91-8595147850" },
  task: async ({ payload }) => {
    console.log("Send follow-up to", payload.phone);
  },
});
```

### Repeat a Job

```ts
await cron.every("cache-refresh", {
  intervalMs: 60_000,
  preventOverlap: true,
  task: async () => {
    console.log("Refresh cache");
  },
});
```

### Queue Work with Priority

```ts
cron.queue("invoice-queue", {
  concurrency: 5,
  maxSize: 1000,
  rateLimit: { limit: 100, intervalMs: 60_000 },
  retry: { attempts: 3, backoff: "linear", delayMs: 1000, jitter: 0.15 },
  processor: async ({ payload }) => {
    console.log("Generate invoice", payload);
  },
});

await cron.addJob("invoice-queue", {
  name: "invoice-5001",
  priority: 10,
  payload: { invoiceId: 5001 },
});

console.log(cron.getQueueStats("invoice-queue"));
cron.pauseQueue("invoice-queue");
cron.resumeQueue("invoice-queue");
```

### Worker Thread Module

```ts
const workerResult = await cron.runWorker("heavy-csv-job", {
  payload: { filePath: "./large.csv" },
  timeout: 60_000,
  worker: {
    path: new URL("./workers/csvWorker.js", import.meta.url),
    exportName: "processCsv",
  },
});
```

```ts
// workers/csvWorker.ts
export async function processCsv({ payload }: { payload: { filePath: string } }) {
  return { processed: true, filePath: payload.filePath };
}
```

## Connect with React or Any Frontend

SilentCronX runs in Node.js. A React, React Native, Android, or web client should call your backend API, and the backend should trigger or inspect jobs.

### Native SilentCronX Client

```ts
import { createSilentCronXClient } from "silent-cronx";

const client = createSilentCronXClient({
  baseUrl: "http://localhost:4517",
  headers: {
    Authorization: "Bearer YOUR_API_TOKEN",
  },
});

const { jobId } = await client.triggerJob("report", {
  payload: { reportType: "daily" },
  priority: 10,
});

const job = await client.getJob(jobId);
const queueStats = await client.getQueueStats();
const health = await client.getHealth();
```

```ts
// React / latest React app client example
await fetch("/api/jobs/send-report", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ reportType: "daily" }),
});
```

See [examples/live-demo](examples/live-demo/README.md) for a zero-dependency Node demo that exposes HTTP routes and shows how a frontend connects.

### ReactJS Hook Example

```tsx
import { useState } from "react";

type JobResponse = {
  accepted: boolean;
  jobId: string;
};

export function useSilentCronXJob(baseUrl = "") {
  const [loading, setLoading] = useState(false);
  const [jobId, setJobId] = useState<string | null>(null);

  async function triggerReport(reportType: string): Promise<JobResponse> {
    setLoading(true);
    try {
      const response = await fetch(`${baseUrl}/jobs/report`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reportType }),
      });
      const data = (await response.json()) as JobResponse;
      setJobId(data.jobId);
      return data;
    } finally {
      setLoading(false);
    }
  }

  return { loading, jobId, triggerReport };
}
```

### React Native Example

```tsx
import { useState } from "react";
import { Button, Text, View } from "react-native";

const API_BASE_URL = "http://localhost:4517";

export function SilentCronXJobScreen() {
  const [jobId, setJobId] = useState<string | null>(null);

  async function triggerReport() {
    const response = await fetch(`${API_BASE_URL}/jobs/report`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ reportType: "mobile-daily" }),
    });
    const data = await response.json();
    setJobId(data.jobId);
  }

  return (
    <View>
      <Button title="Start SilentCronX Job" onPress={triggerReport} />
      {jobId ? <Text>Job queued: {jobId}</Text> : null}
    </View>
  );
}
```

More details are in [docs/REACT_COMPATIBILITY.md](docs/REACT_COMPATIBILITY.md).

## Response Shape

```json
{
  "jobId": "now_1720000000000_abcd1234",
  "name": "send-welcome",
  "status": "success",
  "result": {
    "sent": true
  },
  "attempt": 1,
  "durationMs": 12,
  "startedAt": "2026-07-15T10:00:00.000Z",
  "finishedAt": "2026-07-15T10:00:00.012Z"
}
```

More response and event details are in [docs/RESPONSE_GUIDE.md](docs/RESPONSE_GUIDE.md).

## Documentation

- [FEATURES.md](FEATURES.md)
- [docs/IMPLEMENTATION_GUIDE.md](docs/IMPLEMENTATION_GUIDE.md)
- [docs/CUSTOMIZATION.md](docs/CUSTOMIZATION.md)
- [docs/RESPONSE_GUIDE.md](docs/RESPONSE_GUIDE.md)
- [docs/REACT_COMPATIBILITY.md](docs/REACT_COMPATIBILITY.md)
- [docs/KEYWORDS_AND_HASHTAGS.md](docs/KEYWORDS_AND_HASHTAGS.md)
- [examples/live-demo/README.md](examples/live-demo/README.md)
- [examples/reactjs/useSilentCronXJob.ts](examples/reactjs/useSilentCronXJob.ts)
- [examples/reactjs/SilentCronXDashboard.tsx](examples/reactjs/SilentCronXDashboard.tsx)
- [examples/react-native/SilentCronXJobScreen.tsx](examples/react-native/SilentCronXJobScreen.tsx)
- [DONATION.md](DONATION.md)
- [COPYRIGHT.md](COPYRIGHT.md)
- [CHANGELOG.md](CHANGELOG.md)

## API Surface

- `createSilentCronX(config)`
- `new SilentCronX(config)`
- `createSilentCronXClient(config)`
- `cron.schedule(name, options)`
- `cron.delay(name, options)`
- `cron.every(name, options)`
- `cron.runNow(name, options)`
- `cron.runWorker(name, options)`
- `cron.queue(name, options)`
- `cron.addJob(queueName, job)`
- `cron.pauseQueue(queueName)`
- `cron.resumeQueue(queueName)`
- `cron.clearQueue(queueName)`
- `cron.getQueueStats(queueName?)`
- `cron.cancel(jobId)`
- `cron.pause(jobId)`
- `cron.resume(jobId)`
- `cron.getStatus(jobId)`
- `cron.getJobs()`
- `cron.getHealth()`
- `cron.start()`
- `cron.stop()`
- `cron.shutdown()`
- `cron.on(eventName, handler)`
- `cron.off(eventName, handler)`
- `cron.getEventHistory(eventName?)`
- `cron.clearEventHistory()`

## Production Checklist

- Keep job handlers idempotent.
- Validate user payloads before enqueueing jobs.
- Set timeout and retry limits for every external operation.
- Use `preventOverlap` for billing, reports, sync, and other critical jobs.
- Use persistent custom storage for multi-instance production systems.
- Subscribe to `job:failed`, `job:timeout`, and `error` events.
- Call `shutdown()` on `SIGINT` and `SIGTERM`.
- Use worker module references for CPU-heavy work.

## Development

```bash
npm install
npm run typecheck
npm run build
npm run pack:dry
```

## Hashtags

`#SilentCronX` `#NodeJS` `#TypeScript` `#CronJobs` `#BackgroundJobs` `#WorkerThreads` `#QueueSystem` `#Scheduler` `#ReactJS` `#ReactNative` `#AndroidJava` `#BSGTechnologies` `#PradeepKumarSheoran`
