Skip to content

Instantly share code, notes, and snippets.

@glafarge
Created March 31, 2016 11:07
Show Gist options
  • Save glafarge/7fdbe30b69c0781f921fefbec4092e99 to your computer and use it in GitHub Desktop.
Save glafarge/7fdbe30b69c0781f921fefbec4092e99 to your computer and use it in GitHub Desktop.
Using CRON with CakePHP 3.x if you want to call a controller/action quickly

CRON Dispatcher

  • Create src/webroot/cron_dispatcher.php

  • Now we can use a CLI to run our Crawler controller 'run' action :

php -q /some/absolute/path/myapp/webroot/cron_dispatcher.php /crawler/run

More info on CRON : https://en.wikipedia.org/wiki/Cron

<?php
$_SERVER[ 'HTTP_HOST' ] = 'localhost'; // or something like yourdomain.tld
require dirname(__DIR__) . '/config/bootstrap.php';
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\Routing\DispatcherFactory;
if(PHP_SAPI == "cli" && $argc == 2) {
$dispatcher = DispatcherFactory::create();
$dispatcher->dispatch(
new Request($argv[1]),
new Response()
);
}
else {
exit;
}
@k-risc
Copy link

k-risc commented Feb 3, 2017

Thanks, this was very helpful. In my case I had to extend this code a little. Creating a new request object did not automatically parse the url ($argv[1]) and set the controller and action from it.

What I came up with is:

    $request = new Request($argv[1]);
    $request = $request->addParams(
        Router::parse(
            $request->url,
            ''
        )
    );
    $dispatcher->dispatch(
	    $request,
	    new Response()
	);

@sunnysood1may
Copy link

Hi guys

I am trying to set cron in cakephp 3 in cpanel. but its not working. can anyone help me please

Thanks

@watchowl
Copy link

watchowl commented Nov 9, 2017

@sunnysood1may
We made this plugin to make scheduling/running cron job in CakePHP 3 easy.
Check it out at https://github.com/watchowl/cake-scheduler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment