I have cPanel on a shared server and I need to run a shell script everyday.
This script has to call a controller function that scraps a webpage everyday.
My problem is that I don't know how to do a shell script that calls this function and add it at cron jobs in cpanel. How do I do all of this?
Thanks in advance!
I'm going to extend my question.
I have this code "TestTask.php":
class TestTask extends Shell {
function main() {
$this->out('Hello world.');
}
function execute() {
$this->out('Hello world 2.');
}
}
It's located in: /home/myuser/public_html/app/Console/Command/Task
And then, my cronjob is like this:
* * * * * php /home/myuser/public_html/app/Console/cake.php test -app /home/myuser/public_html/app >> /home/myuser/public_html/file.log
The last part it's to log the output in a file.
It doesn't work at all.
Help please!!!
Here's the command for a cron job I am using on my server:
/home/path-to-cake/lib/Cake/Console/cake -app /home/path-to-cake/app time
where time is my shell, located in /app/Console/Command/TimeShell.php. This is how you run shells.
Now, on the other part of your question, a task must be called from within a shell. From the code you posted, it seems that you are confusing a bit shells with tasks. A shell can contain tasks, just like controllers can have components. main(); is required for a shell when it is called without any arguments. It is not necessary for a task to implement it. On the other hand, a task must implement an execute(); method.
In order to run a task from your shell, be sure to add public $tasks = array('Test'); in the TestShell class; You can use this task in your shell just like you use a component in a controller: $this->Test->whatever();
For more info on CakePHP 2.0 shells and tasks, have a look here
Hope this helped!
Related
I'am developing a project in laravel 5.3 where in a particular command that I created prints "Hello".
I want this command to be called after every 1 minute.
I know in linux you can use cron to schedule the tasks but I'am using windows so I used the windows taks to schedule a .bat file to run after every 1 minute,but it doesnt work.
My .bat file looks like this
cd c:\Users\User\Desktop\alerts
C:\wamp64\bin\php\php7.0.10\php.exe artisan schedule:run 1>> NUL 2>&1
The schedule function in the Kernel.php looks like this:
protected function schedule(Schedule $schedule)
{
$schedule->command('custome:command')->everyMinute();
}
And the actual task that will be called looks like this
public function handle()
{
echo 'Hello';
}
It doesn't give any output. It should automatically print "Hello" after a minute right? But it doesn't. Where is the output shown?
I am going to simplify the process for you.
The content of your .bat file should rather be
"C:\wamp64\bin\php\php7.0.10\php.exe" "c:\Users\User\Desktop\alerts\artisan" "schedule:run"
NB: According to the directories from your question.
Create a task and call this .bat file as an "Action" in the Task Scheduler on your windows.
public function handle(){ logger("Hello"); }
The logger function will output your message to the default laravel log file "laravel.log" for u to see at the bottom.
Hope it helps others too.
Original Post
Good evening folks. I have a laravel setup and I'm trying to have a cronjob execute a php function to a file within the laravel project directory.
I am getting class and name space errors when I try to do something like this:
<?php
require_once('../laravel/app/Http/Controllers/NotificationsController.php');
and then calling the processQueuedNotifications() function.
This of course gives me errors, what is the correct way to call my function within the laravel directory? I need to call this function as this function has all the correct namespaces and extended controllers necessary to execute the function properly.
Update 1:
Thanks to #michael, I've been made aware of a component in Laravel called commands.
So I ran this code:
php artisan make:console processQueuedNotifications
and it created some files in the console directory.
Currently exploring on what to do next.
After checking out the Events class which the kernel.php file makes use of, I noticed that this class provides an easy to use interface for me to create cron jobs on the fly. Am I correct in think so?
I notice there is not function to run a cron job every minute, is it safe to edit the Events class file without it being overwritten by future make:console commands, or laravel updates?
I saw this code in the kernel.php file:
$schedule->command('inspire')
->hourly();
So is this the place you wanted me to add my function? as I notice that the inspire function is something automatically created for me to understand what's going on?
So I would write,
$schedule->command('processQueuedNotifications')
->everyMinute();
//Providing it's safe to edit the Event's class or figure out a clean way of doing so without my code being deleted in the future on Laravel updates.
A very convenient way is to use laravels console component. You can create a new command by issuing
php artisan make:console
And find it thereafter in your app/console directory. Make sure to enable the command in the Kernel.php file once created.
Simply call your class or whatever you want to run via cron from inside the command. The console command itself is callable via cli just as you would run one of laravels php artisan ... commands. You can set this in the file created for you. For example, you can then call the file from everywhere you want with
/usr/bin/php /path/to/file/artisan my:command
You can set options and arguments if you need to.
Here's the documentation: http://laravel.com/docs/5.0/commands / http://symfony.com/doc/current/components/console/introduction.html
There's an array in kernel.php you need to register your class (include the namespace) in. After that it is callable via cli. For a start, have a look on arguments and options you can initialize in case you need to make different requests on your controller class. (The filename you have chosen for your console command, is an argument. You can make them required or optional for your own commands. )
Within your file, you can create them by simply creating an array in the appropriate method with these values:
[$name, $mode, $description, $defaultValue]
have a look at the docs or Jeffrey's laracasts, they are very good.
To only call your class from the console command, it's enough to name your command in the above section of the file and call you controller like
(new namespace\controller)->method();
What you can do in your code, after your update, 2 choices :
Dispatching directly the command from your code using the Bus facade
first import it using the
use Illuminate\Support\Facades\Bus;
then in your code
Bus::dispatchNow(new YourCommandClass);
(don't forget to import your command class)
Dispatch it for queue process using the same bus facade:
(still importing the same way)
Bus::dispatch(new YourCommandClass);
(Note that in that case, you'll need to have the following command run by your cron job :
php artisan queue:listen
it can handle several options such as the --tries=X where is is the number of tries etc
Generally speaking, you can get more info from commands typing php artisan my:command -h
I have a problem figuring out how make my command work, because I only have access via ftp.
The action is pretty simple:
public function actionRun($action = "default") {
$this->xml = simplexml_load_file('db.xml');
return $this->{$action}(); // executes the default() method
}
All I need is to somehow execute the php index.php mycommand run, but I'm lost as to how. This command should only be run once in the life of the whole app.
My question is, is it possible to run such a command? Maybe somehow invoke it through php?
Yii command line command are designed to run through Yii.
$ cd protected
$ ./yiic --help
$ ./yiic mycommand
If you only have ftp access, you may be out of luck, and will have to use some workaround, for example running a cron job, or creating a web page that invokes the last command in the code sample I provided.
echo exec('/my_yii_dir/protected/yiic mycommand');
I wanted to ask how automation of tasks aka cronjobs on a website are run using laravel commands?
I created a command following the tutsplus tutorial and call my functions in the fire method below:
public function fire()
{
$feeds= new FeedsController;
$update='update';
$feeds->getUpdateYoutube($update);
$feeds->getUpdateInstagram($update);
$feeds->getUpdateTwitter($update);
$feeds->getUpdateFacebook($update);
$feeds->getWriteToFile();
$this->info('Success');
}
However, this does not get called at all, despite the fact I included it called it on the server like so: 0 */2 * * * php /home/path/public_html/website artisan feeds-refresh
any clues what I am doing wrong?
I have attempted to create a cron job in my CakePHP 2.x application. But all of the resources I have read online seem to be either doing it completely different to one another with little consistency or explain it in very complex terminology.
Basically I have created the following file MyShell.php in /app/Console/Command
<?php
class MyShell extends Shell {
public function sendEmail() {
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail();
$email->from('cameron#driz.co.uk');
$email->to('cameron#driz.co.uk');
$email->subject('Test Email from Cron');
$result = $email->send('Hello from Cron');
}
}
?>
And I want to say run this code at midnight every night.
What do I do next? As the next part really confuses me! I have read on the Book at: http://book.cakephp.org/2.0/en/console-and-shells/cron-jobs.html that I should run some code in the terminal to make it do it at a certain time etc. And I can set these up using my hosting provider rather easily it seems.
But I'm rather confused about the Console directory. What should go in what folder in here: https://github.com/cakephp/cakephp/tree/master/app/Console
/Console/Command
/Console/Command/Tasks
/Console/Templates
Also noticed that many of the files are .php (e.g. my Shell file is also .php), but according to documentation I've read for Cron jobs, the executed files should be .sh?
Can anyone shed more light on this?
And what would the code be to call that command?
e.g. would presume this is incorrect: 0 0 * * * cd /domains/driz.co.uk/html/App && cake/Console MyShell sendEmail
Thanks
No. There is no way to do it just in PHP. But that doesn't matter, because crons are easy to set up.
In that article you linked to, you still have to set up a cron - the difference is just that you set up a single cron, that runs all your other crons - as opposed to setting up one cron per job. So, either way, you have to learn to create a cron.
The instructions depend on your server's operating system and also what host you're with. Some hosts will have a way to set up cron jobs through a GUI interface like cPanel or something, without you having to touch the terminal.
It's usually pretty easy to find instructions online for how to set up cron jobs with your host or server OS, but if you're having trouble, update your question with your host's name, and your server OS and version.
Also ---------------------------------
Often in cron jobs you'll be running a shell script (.sh). But don't worry about that for this case; your's will end in .php.
Re: the directory structure:
/Console/Command is where your new file should go.
If you're doing a lot of shell stuff, you may want to abstract common code out into the /Console/Command/Task folder. Read more about that here. This probably won't be needed in your case.
/Console/Command/Templates is where you can put custom templates for the Cake bake console - don't worry about that for now.
If I've only got a couple of cron jobs to run, then I create just one file called CronJobsShell.php, and put them all in there.
Really, you should read Cake's documentation on shells from start to end. It will give you a nice picture of how it all hangs together.
This can be done very easily by the following steps -:
1) Create a shell let's say HelloShell.php in Console/Command
<?php
class HelloShell extends AppShell
{
public function main()
{
//Your functionality here...
}
}
?>
This shell can be called by Console/cake hello
2) Write the command crontab-e .This will open up the default editor or the editor which you select Now as we want that our shell should run after at midnight write:-
0 0 * * * /PATH TO APP/Console/cake hello
For better understanding refer https://www.youtube.com/watch?v=ljgvo2jM234
Thanks!