michelle
11/23/2016 - 10:59 AM

Crontab

Crontab

<?php

/**
 * Task controller
 * add to routes.yml something like:
 * 'task/rank': 'RankUsers_Task'
 *
 * Class RankUsers_Task
 */
class RankUsers_Task extends Controller
{

	public function init() {

		parent::init();

		//if this is not a command line call (ie browser), check user is logged in as admin
		if (php_sapi_name() != "cli") {
			if (!Member::currentUser()) {

				return Security::PermissionFailure($this->controller, 'You must be logged in to access this page');
			}

			if (!Member::currentUser()->inGroups(array('administrators'))) {
				return Security::PermissionFailure($this->controller, 'You must be logged in as admin to access this page');
			}
		}
	}

	//nice simple, allow index function as default
	public static $allowed_actions = array('index');

	// Run as:
	// 1 * * * * php /var/www/html/framework/cli-script.php task/TestTask >> /var/www/log/cronlog.txt 2>&1; echo "" >> /var/www/ log/cronlog.txt
	// this means it runs at 10mins past every hour, every day, every month and logs things to cronlog.txt with a blank line between each entry
	// Your should be able to run this part successfully in terminal to check the command will work: php [full path to site]/framework/cli-script.php task/rank
	public function index()
	{
		//run a task
		new Ranking(Student::get()->filter('Deleted', 0));

		//output something to log
		echo date('Y-m-d H:i:s') . ': Leaderboard updated';
	}

}
To create a crontab 

1. From vagrant box run 'crontab -e' to show a list of current cronjobs.
2. To add a new one: 
    'SHIFT & i', 
    add job: 1 * * * * php /var/www/html/framework/cli-script.php task/TestTask >> /var/www/log/cronlog.txt 2>&1; echo "" >> /var/www/ log/cronlog.txt
    ESC then ENTER
    :wq
3. This sets it to run every minute.
4. To check task can execute copy php to task section in terminal
5. Then check it can create a log file by running the full job minus the time interval
6. If it can't create a log file, check what permissions are on the log file and if necessary amend them to chmod 777 
7. ">>" This directs and outputs any on screen output to a file.
8. "2>&1;" This directs and outputs any on screen errors to a file.