# Farm Control Scheduler [![Build Status](https://ci.tombutcher.work/buildStatus/icon?job=farmcontrol%2Ffarmcontrol-scheduler%2Fmain&style=flat-square)](https://ci.tombutcher.work/job/farmcontrol/job/farmcontrol-scheduler/job/main/) A background service for Farm Control ERP that fires time-sensitive events on model objects once their scheduled date/time has passed. ## Features - Scans configured models for scheduled properties (e.g. a "publish at" or "expires at" date) and picks up any that are now due. - Runs the scheduling loop on a dedicated worker thread, so checks never block the main application event loop. - Calls `onSchedulerEvent(property, value)` on the relevant model instance once its scheduled time arrives. ## How it works 1. On startup, `SchedulerManager` inspects every registered model for a `scheduledProperties` definition and queries the database for any matching objects that are due (or already overdue). 2. Each match is wrapped in a `Scheduler` (`id`, `objectType`, `object`, `property`, `value`) and added to the manager's schedulers list. 3. A worker thread (`schedulerWorker.js`) polls the list on an interval, comparing each scheduler's `value` against the current date/time. 4. When a scheduler is due, the worker notifies the main thread, which calls `object.onSchedulerEvent(property, value)` and removes the scheduler from the list. Models opt in to this behaviour by defining `scheduledProperties` on their Mongoose schema and implementing an `onSchedulerEvent(property, value)` method to handle the callback. ## Prerequisites - Node.js (v16 or higher) - MongoDB server - Redis server ## Installation 1. Clone the repository 2. Install dependencies: ```bash npm install ``` ## Configuration The application uses `config.json` for configuration. At minimum it expects a `server` block controlling logging, plus connection details for MongoDB and Redis: ```json { "server": { "logLevel": "debug" }, "mongo": { "uri": "mongodb://localhost:27017/farmcontrol" }, "redis": { "host": "localhost", "port": 6379 } } ``` See `config.js` for the full set of supported options. ## Running the Application ### Development ```bash npm run dev ``` ### Production ```bash npm start ``` ## Logging The application uses [log4js](https://log4js-node.github.io/log4js-node/) for logging. Set the log level under `server.logLevel` in your configuration: ```json { "server": { "logLevel": "debug" } } ``` Available log levels (least to most verbose): `error`, `warn`, `info`, `debug`, `trace`.