peppeocchi / php-cron-scheduler

PHP cron job scheduler
MIT License
808 stars 143 forks source link

Error when Scheduling an Object Method using ->call() #140

Open aldisaglobal opened 1 year ago

aldisaglobal commented 1 year ago

I encountered the following error:

PHP Fatal error:  Uncaught Exception: Serialization of 'Closure' is not allowed in /www/vendor/peppeocchi/php-cron-scheduler/src/GO/Job.php:161

Here is my code that is generating this error:

class Cron
{
    private $container;
    private $jobs;

    public function __construct()
    {
        // initialize the container
        $builder = new ContainerBuilder();
        $builder->addDefinitions(APP_ROOT . '/boot/definitions.php');
        $this->container = $builder->build();
    }

    public function run()
    {
        // load crontab
        $this->jobs = $this->container->get('crontab');
        if (!is_array($this->jobs) || count($this->jobs) === 0) {
            return;
        }
        // load the scheduler
        $scheduler = new Scheduler();

        // process the crontab file
        $classpath = '\\App\\Tasks\\';
        foreach ($this->jobs as $i => $job) {

            // init cron function
            if (!array_key_exists('task', $job) || !array_key_exists('schedule', $job)) {
                continue;
            }

            $class = "{$classpath}{$job['task']}";
            if (!class_exists($class) || !is_a($class, '\\App\\Abstract\\AbstractTask', true)) {
                continue;
            }
            $this->jobs[$i]['obj'] = new $class($this->container);

            // add job to scheduler
            $scheduler->call(
                array($this->jobs[$i]['obj'], 'execute'),
            )->at($job['schedule']);

        }

        // run the scheduler
        $scheduler->run();
    }
}

From what I can understand, the error arises when your code tries to generate a unique id for the job by serializing the callable array. The problem might be related to the fact that my object is stored with an array.

My suggestion is that using the uniqid function to generate job ids may be a safer approach.

For now, I am able to work around this error by passing in an id to the scheduler for each job.