{"id":20757503,"url":"https://github.com/incapption-public/loadbalancedcrontask","last_synced_at":"2025-12-24T11:55:05.821Z","repository":{"id":56990786,"uuid":"456898285","full_name":"incapption-public/LoadBalancedCronTask","owner":"incapption-public","description":"This is a lightweight package for load balancing your cron tasks. It is used to distribute tasks across a network of identical servers to make sure they are run only once and not multiple times.","archived":false,"fork":false,"pushed_at":"2022-06-01T14:50:32.000Z","size":1576,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-02-18T10:18:22.369Z","etag":null,"topics":["cron","cronjob","cronjob-handler","cronjob-scheduler","crontab","loadbalance","loadbalancer","loadbalancing","mysql","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/incapption-public.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-02-08T11:09:16.000Z","updated_at":"2025-02-12T11:53:00.000Z","dependencies_parsed_at":"2022-08-21T13:50:11.121Z","dependency_job_id":null,"html_url":"https://github.com/incapption-public/LoadBalancedCronTask","commit_stats":null,"previous_names":["incapption-public/loadbalancedcrontask"],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/incapption-public%2FLoadBalancedCronTask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/incapption-public%2FLoadBalancedCronTask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/incapption-public%2FLoadBalancedCronTask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/incapption-public%2FLoadBalancedCronTask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/incapption-public","download_url":"https://codeload.github.com/incapption-public/LoadBalancedCronTask/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243067044,"owners_count":20230858,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cron","cronjob","cronjob-handler","cronjob-scheduler","crontab","loadbalance","loadbalancer","loadbalancing","mysql","php"],"created_at":"2024-11-17T09:42:59.817Z","updated_at":"2025-12-24T11:55:05.778Z","avatar_url":"https://github.com/incapption-public.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Load Balanced Cron Task\n\n## Introduction\nThis is a lightweight package for load balancing your cron tasks. It is used to distribute tasks \nacross a network of **identical servers** to make sure they are run only once and not multiple times. \n\u003eIt is important that your application network uses only one single central mysql database. \nA table is created in the database in which current tasks are inserted. \nA primary key ensures that the task only runs once (a kind of locking process).\n\u003e \n\u003e the ***unique_hash*** is a md5 hash of the task name, the schedule and the current timestamp ***without*** seconds. With this, the nodes can run asynchronously but the task runs only once at a time.\n\n---\n\n### Scheme of operation\n\n![alt text](scheme.png)\n\n## Requirements\n- MySQL Database\n- PHP PDO Extension (ext-pdo, ext-pdo_mysql)\n\n## 1. Installation\n\n### 1.1 Composer\n\nInstall `Load Balanced Cron Task` using Composer.\n\n```bash\n$ composer require incapption/load-balanced-cron-task\n```\n\n### 1.2 Create MySQL Table\n\nThis package needs a small table in your database. \nIt's used for locking running tasks, to make sure that only on app instance could run it.\n\n```sql\nCREATE TABLE IF NOT EXISTS `lbct_tasks` (\n`id` int(11) NOT NULL AUTO_INCREMENT,\n`unique_hash` varchar(32) NOT NULL,\n`task` varchar(256) NOT NULL,\n`schedule` varchar(256) NOT NULL,\n`date_created` datetime NOT NULL,\n`worker` varchar(256),\nPRIMARY KEY (`unique_hash`),\nKEY `id` (`id`)\n);\n```\n\n### 1.3 Install Crontab\n\nThe idea is that you have only one single cron task running every minute. \nThis cron task contains all other tasks wrapped by **LoadBalancedCronTask**\n\nOpen your crontab console (e.g. linux: ```crontab -e```)\n```bash\n* * * * /usr/bin/php /your/local/path/cron.php\n```\n\n### 1.4 Create your cron file\n\nMaybe you want to integrate into your application, or you create a new plain file.\n\n```php\n\u003c?php\n\nuse Incapption\\LoadBalancedCronTask\\Abstracts\\CronTaskAbstract;\nuse Incapption\\LoadBalancedCronTask\\LoadBalancedCronTask;\nuse Incapption\\LoadBalancedCronTask\\Exceptions\\LoadBalancedCronTaskException;\n\nrequire_once('./vendor/autoload.php');\n\nclass TestCronTask extends CronTaskAbstract\n{\n    public function __construct()\n    {\n        $this-\u003ename = 'TestCronTask';\n    }\n\n    public function task(): bool\n    {\n        // do your cron task\n        return file_put_contents('test.html', 'awesome! it works! '.date('Y-m-d H:i:s', time()));\n    }\n}\n\ntry {\n    $response = (new LoadBalancedCronTask())\n        -\u003emysql($_ENV['MYSQL_HOST'], $_ENV['MYSQL_USER'], $_ENV['MYSQL_PASSWORD'], $_ENV['MYSQL_DATABASE'])\n        -\u003esetWorkerName('Node 1')\n        -\u003etask((new TestCronTask()))\n        -\u003eloadBalanced()\n        -\u003eeveryMinute()\n        -\u003erun();\n} catch (LoadBalancedCronTaskException $e) {\n    exit($e-\u003egetMessage());\n}\n```\n___\n\n## 2. How to use it\n\nAs shown in the example above you need to create classes for your cron tasks that extends ***CronTaskAbstract***. \nDefine the behavior in the ***task()*** method.\n\nSecond create the load balanced cron task.\n\n```php\n# Example for a distributed load balanced cron task\n \n$response = (new LoadBalancedCronTask())\n    -\u003emysql($_ENV['MYSQL_HOST'], $_ENV['MYSQL_USER'], $_ENV['MYSQL_PASSWORD'], $_ENV['MYSQL_DATABASE'])\n    -\u003esetWorkerName('Node 1')\n    -\u003etask((new TestCronTask()))\n    -\u003eloadBalanced()\n    -\u003eeveryMinute()\n    -\u003erun();\n\n# Example for a local cron task\n \n$response = (new LoadBalancedCronTask())\n    -\u003etask((new TestCronTask()))\n    -\u003elocal()\n    -\u003eeveryMinute()\n    -\u003erun();\n```\n\n### 2.1 Chainable methods\n\n#### General:\n\n| Method | Description                                                                                                                                                  |\n| ----------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| -\u003emysql(string $host, string $user, string $password, string $database) | Sets the mysql credentials for the underlying pdo instance                                                                                                   |\n| -\u003esetWorkerName(string $name) | Sets the name of the current worker. Perhaps you will use a environment variable                                                                             |\n| -\u003etask(CronTaskAbstract $task) | Awaits an instance of CronTaskAbstract                                                                                                                       |\n| -\u003elocal() | Sets the cron task to ***local***. No distributing and load balancing is taking place. Useful for node specific tasks such as cleaning local tmp folder etc. |\n| -\u003eloadBalanced() | Sets the cron task to ***load balanced***. The task is distributed around the network. Only one worker runs the task at a time.                              |\n\n#### Scheduling methods:\n\n| Method | Description |\n| ----------- | ----------- |\n| -\u003eeveryMinute() | Run the task every minute |\n| -\u003eeveryTwoMinutes() | Run the task every two minutes |\n| -\u003eeveryThreeMinutes() | Run the task every three minutes |\n| -\u003eeveryTenMinutes() | Run the task every five minutes |\n| -\u003eeveryFifteenMinutes() | Run the task every fifteen minutes |\n| -\u003eeveryThirtyMinutes() | Run the task every thirty minutes |\n| -\u003ehourly() | Run the task every hour |\n| -\u003ehourlyAt(17) | Run the task every hour at 17 minutes past the hour |\n| -\u003edaily() | Run the task every day at 00:00 |\n| -\u003edailyAt('17:13') | Run the task every day at 17:13 o'clock |\n| -\u003emonthly() | Run the task on the first day of every month at 00:00 |\n| -\u003emonthlyOn(4, '15:00') | Run the task every month on the 4th at 15:00 |\n| -\u003elastDayOfMonth('15:00') | Run the task on the last day of the month at 15:00 |\n| -\u003elastDayOfMonthOffset(2, '15:00') | Run the task on the last day of the month at 15:00 with an offset of 2 days. As an example: ***lastDayOfMonthOffset(2, '15:00')*** in january, which has 31 days, runs on the 29th at 15 o'clock|\n\n\u003e Be careful with the days 29th, 30th, 31st if you use ***monthlyOn()***. Maybe use ***lastDayOfMonth()*** or ***lastDayOfMonthOffset()*** instead.\n\n___\n\n### 3. Exceptions\nAn instance of **LoadBalancedCronTask()** throws a **LoadBalancedCronTaskException** when there is something wrong inside the logic for everything else you can use the default **PHP Exceptions**.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fincapption-public%2Floadbalancedcrontask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fincapption-public%2Floadbalancedcrontask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fincapption-public%2Floadbalancedcrontask/lists"}