How to use Phalcon's task scheduler?

by hal.littel , in category: PHP Frameworks , a year ago

How to use Phalcon's task scheduler?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a year ago


Phalcon provides a built-in task scheduler that allows you to schedule tasks to run at specific times or intervals. To use the task scheduler in Phalcon, follow these steps:

  1. Create a new class that extends the PhalconCliTask class. This class will contain the logic for the task you want to run.
  2. Define a method inside your task class that will be executed when the task runs. This method must have a public visibility modifier and be named mainAction().
  3. In your application's bootstrap file or an appropriate service provider, register the task manager. Here is an example: $di->setShared('taskManager', function () { return new PhalconCliTaskManager(); });
  4. Schedule the task to run by calling the task manager's add() method and passing in the task class name, the method to run and the schedule for running the task. Here is an example: $taskManager = $this->getDI()->getShared('taskManager'); // Run the task every minute $taskManager->add(new MyTask(), 'main', '* * * * *'); In the above example, MyTask is the name of the task class, main is the method that will be run in the task class and '* * * * *' is the cron expression that specifies when the task should be run.
  5. Run your task scheduler by calling the task manager's run() method. Here is an example: $taskManager->run(); This will start the task scheduler and run the tasks at their scheduled times.

That's it! You now have a working task scheduler in your Phalcon application.