I have use carbon, but it's not working according to my needs.
What I want is to apply check on time in minutes, like after every 15 min check, to work and then minute reset to zero.
Like:
if(time > 15 ) {
do this...
reset to zero
} else {
do this
}
You need task schedule or command make:
The simple form is call your controller every15min, go to app/console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->call('yourcontroller#youtfunction')->everyFifteenMinutes();
}
And you run this: php artisan schedule:run
You can make command, but this ius more complex
Here is oficial documentation: https://laravel.com/docs/7.x/scheduling
Related
In my laravel project, I have this file in my tests directory:
tom_test.php:
<?php
error_log("hello world");
I want to schedule this script to run every 'x' amount of time.
I've seen this question from cyber8200.
Unfortunately, I'm unsure how to make this test script to run.
Do I have to convert the test file to a class instead?
I would appreciate it if somebody would explicitly state what code needs to be added to the app/Console/Kernel.php file.
I suspect it should resemble some of the code in the cyber8200 question
UPDATE
Thanks to Tim Lewis' comment, I've managed to get the cron job running (I think).
Unfortunately, I cannot see the "hello world" message being logged to the console.
Here is what I've done
I added a command as follows:
public function handle()
{
error_log("hello");
// echo base_path();
exit;
include base_path().'/tests/Browser/tom_test.php';
}
and this schedule function to the kernel:
protected function schedule(Schedule $schedule)
{
$schedule->command('tom_test')
->everyMinute();
}
This is the result I get:
The job seems to be quitting after one run, and no message is logged to the console.
It seems that only everyMinute() and cron('* * * * *') are working for me. Any other methods like everyFiveMinutes, everyTenMinutes, daily, dailyAt etc, aren't working at all and always return "No scheduled commands are ready to run". My cron entry is always * * * * * so the other methods should work as well right? And yes; I've actually tried waiting for the other methods including daily, excluding yearly :P
Cron entry: * * * * * /opt/alt/php72/usr/bin/php /home/retracted/domains/retracted/artisan schedule:run >> /dev/null 2>&1
Schedule entry:
$schedule->call(function () {
$stat = new Stat();
$stat->users = User::count();
$stat->reviews = Review::count();
$stat->scholen = School::count();
$stat->save();
})->daily();
So my questions: Why don't the other methods work? How do I make the other methods work, especially daily()?
So first you have to run your cronjob every minute that is correct. With that line you run your Laravel scheduler.
So i don't know the scheduler code but it's possible that the code runs only on that minute and not backwards.
So if you need a 5 minute cronjob you have to run your scheduler every minute and then define your duration in your scheduler task.
$schedule->call(function () {
$stat = new Stat();
$stat->users = User::count();
$stat->reviews = Review::count();
$stat->scholen = School::count();
$stat->save();
})->everyFiveMinutes();
So with the function ->everyFiveMinutes(); you can run the scheduler every five minutes.
For laravel custom cron jobs to work you have to do the following:
First setup an every minute cron by executing the command "crontab
-e" and adding the following line * * * * * php /var/www/html/crontutorial/artisan schedule:run >> /dev/null 2>&1
Configure the appropriate timezone on app/config.php eg 'timezone'
=> 'Europe/Berlin',
Create a custom command that you want to execute at a specific time.
If you don't know how to create custom commands please have a look
at laravel cronjob scheduling tutorial
Schedule custom crons in app/Console/Kernel.php by adding the
following lines of code
protected function schedule(Schedule $schedule)
{
$schedule->command('my:customcommand')
->cron('01 13 * * *');
}
The cron will run every day 1.13pm using the timezone configuration in app/config.php.
Did you try specifying with the timezone? Check the below working snippet from my project:
protected function schedule(Schedule $schedule)
{
try{
$schedule->call(function (){
(new MTSnapshot)->createSnapshot();
})->timezone('Asia/Kolkata')->dailyAt('23:57');
$schedule->call(function (){
(new MTTransaction)->schedulerStatus();
})->hourly();
$schedule->call(function (){
(new MTTransaction)->syncPendingTransactions();
(new MTCommission)->processPendingCommissions();
})->twiceDaily(1, 16);
} catch(\Throwable $t){
Log::emergency($t);
}
}
I am trying to configure laravel task schedular , I am priting numbers from 0 to infinity to just test why withoutoverlapping() isn't working.
My code :
protected function schedule(Schedule $schedule)
{
$schedule->call(function (Request $request)
{
$i=0;
while(1)
{
echo $i."-";
sleep(3);
$i++;
}
})->everyMinute()->name('mailfetch')->withoutOverlapping();
}
If my schedular is running and I am trying to run another schedular then that should not execute, but in my case both schedulars start running and start priting data.
Output:
Everything seems to be correct but dont' know why is that happening.
It will not overlap only if you launch them in the same minute. Because, you said to your process: "start an infinite loop every minute". So when you run your new instance, maybe you are in a new minute.
If you want to try something about overlapping, you could try:
$schedule->call(function (Request $request) {
echo 'start';
sleep(120);
echo '- end';
})->dailyAt('13:00')->withoutOverlapping();
I have one table called dc_user_meta and I've created one artisan command and scheduled it in kernel.php. Just after cloning the repository, when I try to run PHP artisan migrate, I get this error.
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.dc_user_meta' doesn't exist (SQL: select * from `dc_user_met
a` where `meta_key` = usage_in_days)
Not only php artisan migrate but I am unable to run any artisan command at all! I don't know why PHP keeps calling schedule method every time I try to execute any artisan command.
Here in this case, What I can do to solve this error is put the cover over my logic in schedule method just like this.
if(Schema::hasTable('dc_user_meta')){
// Code here
}
But I don't think it's good in Long run. What's the right way to solve this error?
UPDATE:
I just tried covering call to command in kernel.php just like this but still no success!
if(Schema::hasTable('dc_user_meta')){
$schedule->command('usage:update')->daily();
}
UPDATE:
I got the solution. But I don't think it's the answer to the question. It solves my problem but I don't think it's standard Solution. I just covered by Command login just like this.
if(Schema::hasTable('dc_user_meta')){
// Command Logic
}
Any specific answer to why Laravel calls schedule() with every artisan command and how to solve the error in a standard way if something like this happens!
Technically the schedule method ist called via the constructor of Illuminate\Foundation\Console\Kernel ( This is the parent class of app\Console\Kernel.php)
So every time the console Kernel is instantiated, the schedule() method gets executed.
Let's see what gets executed in which scenario ( $schedule->call() can be replaced with $schedule->command() or $schedule->exec()):
protected function schedule(Schedule $schedule)
{
// everything that is inside the schedule function is executed everytime the console kernel is booted.
// gets exectuted every time
\App\User::where('foo', 1)->get();
$schedule->call(function() {
// gets executed for every call to php artisan schedule:run
\App\User::where('foo', 1)->get();
});
$schedule->call(function() {
// gets executed for every call to php artisan schedule:run
// IF the closure in the when() function is true;
\App\User::where('foo', 1)->get();
})->when(function() {
// if true is returned the scheduled command or closure is executed otherwise it is skipped
\Schema::hasColumn('user', 'foo');
});
}
But why HAS the schedule command to be exectuted with every command?
Well, obviously php artisan schedule:run is a console command itself. So it definitely needs information about scheduled commands.
Also other commands could need information about scheduled commands... For example if you want to write an artisan command list:scheduledTasks. This command would require that all scheduled commands have been added to the console schedule list.
Maybe there are several other (internal) arguments why the schedule function has to run everytime. ( I did not dig too deep in the source code... )
Nevertheless... information about scheduled commands could be useful to a variety of use cases.
Your error is with table dc_user_meta while your logic is of table user_meta you need to do Schema::hasTable('dc_user_meta')
I'm convinced that table dc_user_meta doesn't exist in database.
As I understand, yor have table "user_meta" not "dc_user_meta" but you have written the code to use table "dc_user_meta" hence there is an error saying "dc_user_meta" table not found.
If anyone still cares about this...
<?php
# This is your app/Console/Kernel.php
use ...;
class Kernel extends ConsoleKernel {
# Other stuff...
protected function schedule(Schedule $schedule) {
if( in_array('schedule:run', $_SERVER['argv']) ){
# Your scheduler commands here...
}
}
}
So basically I couldnt find my answer elsewhere. I'm having an issue with Laravel 5.x in where I have models called 'Bumpers' which can have a certain cron-time value (say 'every 25 minutes').
Many bumpers can have the same cron-time, meaning that at a certain time, many of these bumpers may be executed using the Laravel Scheduler. However, I need to run these bumpers 10 seconds apart from eachother. So if 10 bumpers are triggered at 8:00:00PM, I need the queue to run with 10 seconds interval until all bumpers have been executed.
I've tried adding sleep(); to the $schedule->call(function(){executeStuff(); sleep(10)});. That worked for a bit but unfortunately it only works for queues not exceeding 60 seconds because then the Scheduler is ran again:
// This function is called on "artisan schedule:run"
protected function schedule(Schedule $schedule)
{
// Get only the active bumpers.
$bumpers = Bumper::where('status', 1)->get();
// Register all bumpers through their occurrence value.
foreach ($bumpers as $bumper) {
// Check for member/admin. All other bumpers are neglected.
if ($bumper->user->canBump()) {
$schedule->call(function () use ($bumper) {
sleep(10);
$bumper->post();
})->cron($bumper->occurrence);
}
}
}
Any solutions?