Executing php callbacks using cron expression.

# Content

# Setup

Require package

composer require contributte/scheduler
1

Register extension

extensions:
	scheduler: Contributte\Scheduler\DI\SchedulerExtension
1
2

# Configuration

Set-up crontab. Use the scheduler:run command.

* * * * * php path-to-project/console scheduler:run
1

Optionally, you can set a temp path for storing lock files.

scheduler:
	path: '%tempDir%/scheduler'
1
2

# Jobs

This package defines 2 types of jobs:

  • callback job
  • service job

# Callback job

Register your callbacks under scheduler.jobs key.

services:
	stats: App\Model\Stats

scheduler:
	jobs:
		# stats must be registered as service and have method calculate
		- { cron: '* * * * *', callback: [ @stats, calculate ] }

		# monitor is class with static method echo
		- { cron: '*/2 * * * *', callback: App\Model\Monitor::echo }
1
2
3
4
5
6
7
8
9
10

Be careful with cron syntax, take a look at following example. You can also validate your cron using crontab.guru (opens new window).

	*	*	*	*	*
	-	-	-	-	-
	|	|	|	|	|
	|	|	|	|	|
	|	|	|	|	+----- day of week (0 - 7) (Sunday=0 or 7)
	|	|	|	+---------- month (1 - 12)
	|	|	+--------------- day of month (1 - 31)
	|	+-------------------- hour (0 - 23)
	+------------------------- min (0 - 59)
1
2
3
4
5
6
7
8
9

# Custom job

Create new class which implements IJob interface.

use Contributte\Scheduler\IJob;

class ScheduledJob implements IJob
{

	private $dateService;

	private $statisticsService;

	public function __construct($dateService, $statisticsService) {
		$this->dateService = $dateService;
		$this->statisticsService = $statisticsService;
	}

	public function isDue(DateTime $dateTime): bool
	{
		if ($this->dateService->isRightTime($dateTime)) {
			return true;
		}
		return false;
	}

	public function run(): void
	{
		$this->statisticsService->calculate();
	}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Register your class into config.neon as regular services into nette dependency-injection container (opens new window).

scheduler:
	jobs:
		- App\Model\ScheduledJob()
		- App\Model\OtherScheduledJob()
1
2
3
4

You can also reference already registered service.

services:
	scheduledJob: App\Model\ScheduledJob

scheduler:
	jobs:
		- @scheduled
1
2
3
4
5
6

# Console

This package relies on symfony/console, use prepared contributte/console (opens new window) integration.

composer require contributte/console
1
extensions:
	console: Contributte\Console\DI\ConsoleExtension(%consoleMode%)
1
2

After that you can fire one of these commands.

Command Info
scheduler:help Print cron syntax.
scheduler:list List all jobs.
scheduler:run Run all due jobs.
scheduler:force-run Force run selected scheduler job.