Current Location: Home> Latest Articles> Practical Guide to Phalcon Middleware: Easily Implement Scheduled Tasks and Timers

Practical Guide to Phalcon Middleware: Easily Implement Scheduled Tasks and Timers

M66 2025-08-04

Introduction

In web development, executing tasks on a schedule or triggering timers is a frequent requirement. Phalcon, a high-performance PHP framework, supports integrating these features flexibly via middleware, enabling automated processing capabilities in applications.

What is Phalcon Middleware?

Phalcon middleware refers to code modules inserted during the HTTP request lifecycle, executing actions before or after request dispatch. Middleware allows convenient addition and management of scheduled tasks and timers, enhancing extensibility and maintainability.

How to Add Scheduled Tasks

Within Phalcon, registering scheduled tasks through middleware is straightforward. Define the scheduled task function and route requests to the middleware to enable periodic execution.

Example code (PHP):

use PhalconMvcRouter;
use PhalconMvcRouterRoute;

// Define a scheduled task
function myTask() {
    // Task logic here
    echo "Scheduled task executed";
}

// Create middleware to add the scheduled task
$router = new Router();

$router->add(
    '/my/time/task',
    [
        'controller' => 'index',
        'middleware' => function() {
            // Add a scheduled task that runs every minute
            swoole_timer_tick(60000, 'myTask');
        }
    ]
);

// Register the router in the application
$app->getDI()->setShared('router', $router);

In the code above, the swoole_timer_tick function sets up a task running every minute. Routing directs requests to the middleware, effectively integrating the scheduled task.

How to Add Timers

Besides recurring tasks, Phalcon middleware supports one-time timers that execute logic after a specified delay.

Example code (PHP):

use PhalconMvcRouter;
use PhalconMvcRouterRoute;

// Create middleware to add a timer
$router = new Router();

$router->add(
    '/my/time/timer',
    [
        'controller' => 'index',
        'middleware' => function() {
            // Add a timer that triggers after 5 seconds
            swoole_timer_after(5000, function() {
                // Timer logic here
                echo "Timer executed";
            });
        }
    ]
);

// Register the router in the application
$app->getDI()->setShared('router', $router);

The swoole_timer_after function in this example executes a delayed, one-time timer, useful for tasks that require deferred execution.

Conclusion

Phalcon middleware provides a flexible and efficient way to add scheduled tasks and timers to PHP applications. Whether for periodic or delayed execution, combining Swoole timers with middleware offers a reliable solution for task scheduling.