corn expression
Real time application of corn job
How to check url status every hour using corn job
corn expression
The * * * * * syntax in cron represents the schedule for when the cron job should run. It uses the format:
* * * * *
| | | | |
| | | | +--- Day of the week (0 - 6) (Sunday = 0)
| | | +----- Month (1 - 12)
| | +------- Day of the month (1 - 31)
| +--------- Hour (0 - 23)
+----------- Minute (0 - 59)
Here's an example cron job command for Laravel's scheduler:
* * * * * cd /path-to-your-laravel-project && php artisan schedule:run >> /dev/null 2>&1
Explanation:
Every 5 Minutes:
*/5 * * * *
Explanation: This cron expression runs the job every 5 minutes.
Every Day at 3 AM:
0 3 * * *
Explanation: This cron expression runs the job every day at 3:00 AM.
Every Monday at 8 PM:
0 20 * * 1
Explanation: This cron expression runs the job every Monday at 8:00 PM.
Every Last Day of the Month at Midnight:
0 0 28-31 * *
Explanation: This cron expression runs the job on the 28th, 29th, 30th, or 31st day of the month at midnight.
Every Weekday at Noon:
0 12 * * 1-5
Explanation: This cron expression runs the job every weekday (Monday to Friday) at noon.
Every 15th Minute of the Hour:
15 * * * *
Explanation: This cron expression runs the job every hour at the 15th minute.
Every 2 Hours:
0 */2 * * *
Explanation: This cron expression runs the job every 2 hours.
Every Sunday and Wednesday at 4 AM:
0 4 * * 0,3
Explanation: This cron expression runs the job every Sunday and Wednesday at 4:00 AM.
Twice Daily at 8 AM and 8 PM:
0 8,20 * * *
Explanation: This cron expression runs the job twice daily at 8:00 AM and 8:00 PM.
Once a Year on January 1st at Midnight:
0 0 1 1 *
Explanation: This cron expression runs the job on January 1st at midnight.
Real time application of corn job
Cron jobs are widely used in Laravel applications for automating tasks that need to be executed at scheduled intervals. Here are some real-time applications of cron jobs in Laravel with examples:
Sending Scheduled Emails:
Example: Sending a weekly newsletter or a monthly report email to users.
Implementation: Use Laravel's scheduler to run a command that sends the emails at a specific time.
Data Backup:
Example: Regularly backing up the application's database to prevent data loss.
Implementation: Schedule a command to run a database backup script using a package like spatie/laravel-backup.
Cleanup Tasks:
Example: Deleting temporary files or records older than a certain period.
Implementation: Create a command that cleans up the necessary data and schedule it to run daily or weekly.
Cache Clearance:
Example: Clearing the application cache periodically to improve performance.
Implementation: Schedule a command to run Laravel's cache:clear artisan command at specific intervals.
Updating Currency Exchange Rates:
Example: Fetching and updating currency exchange rates daily.
Implementation: Schedule a command that fetches the latest rates from an API and updates the database.
Generating Reports:
Example: Generating and exporting reports for analysis.
Implementation: Create a command to generate reports based on specific criteria and schedule it to run at regular intervals.
Scheduled API Calls:
Example: Fetching data from an external API regularly.
Implementation: Schedule a command to make API requests and update the application's database with the retrieved data.
Rotating Log Files:
Example: Archiving and rotating log files to prevent them from becoming too large.
Implementation: Schedule a command that renames or archives log files based on a defined schedule.
Automated Social Media Posts:
Example: Posting updates or tweets on social media platforms at specific times.
Implementation: Schedule a command to post updates using the social media API.
Session Cleanup:
Example: Clearing expired user sessions to free up resources.
Implementation: Schedule a command to clean up expired sessions at regular intervals.
Updating Search Index:
Example: Updating the search index for search functionality.
Implementation: Schedule a command to rebuild or update the search index daily or weekly.
Automated Notifications:
Example: Sending automated notifications or reminders to users.
Implementation: Schedule a command to check for pending notifications and send them as needed.
How to check url status every hour using corn job
apply bussiness logic in controller
code checks the status of URLs stored in the Guest_post table every 24 hours. It performs a simple HTTP GET request to each URL and updates the status in the database based on the response. Any errors during the process are logged. This is useful for monitoring the reachability of URLs over time
public function updateStatusEvery24Hours()
{
// Get all records from the Guest_post table
$guestPosts = Guest_post::all();
Log::info('Checking status for URLs: ' . json_encode($guestPosts));
foreach ($guestPosts as $post) {
// Check if 24 hours have passed since the last update
$lastUpdated = Carbon::parse($post->updated_at);
$currentTime = Carbon::now();
// if ($currentTime->diffInMinutes($lastUpdated) >= 1) {
// if ($currentTime->diffInHours($lastUpdated) >= 24) {
// // Perform the URL check (similar to your existing logic)
// $isUrlWorking = $this->checkIfUrlIsWorking($post->url);
// // Update the status in the database
// $post->update(['status' => $isUrlWorking]);
// // Log the URL and its status
// Log::info('URL: ' . $post->url . ', Status: ' . ($isUrlWorking ? 'Active' : 'Inactive'));
// }
if ($currentTime->diffInMinutes($lastUpdated) >= 1) {
// Perform the URL check (similar to your existing logic)
$isUrlWorking = $this->checkIfUrlIsWorking($post->url);
// Update the status in the database
$post->update(['status' => $isUrlWorking]);
// Log the URL and its status
Log::info('URL: ' . $post->url . ', Status: ' . ($isUrlWorking ? 'Active' : 'Inactive'));
}
}
Log::info('Status update completed.');
}
protected function checkIfUrlIsWorking($url)
{
try {
// Send a simple GET request and check if it's successful
$response = Http::get($url);
Log::info('Checking status for URL: ' . $url . ', Response: ' . $response->status());
return $response->successful();
} catch (\Exception $e) {
Log::error('Error checking URL: ' . $url . ', Error: ' . $e->getMessage());
return false; // Error occurred, website is not reachable
}
}
Step 2:- Create a command
This command essentially serves as a bridge between the Artisan command-line interface and the updateStatusEvery24Hours method defined in the GuestPostAdminController controller. It allows you to run this specific task from the command line using php artisan guestpost:update-status
php artisan make:command UpdateStatusEvery24Hours
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Http\Controllers\Admin\GuestPostAdminController;
class UpdateStatusEvery24Hours extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'guestpost:update-status';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update status for URLs every 24 hours';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// Create an instance of your controller
$controller = new GuestPostAdminController;
// Call the controller function
$controller->updateStatusEvery24Hours();
$this->info('Status update completed.');
}
}
Step 3:- In your project
The code you provided is from the Kernel class in Laravel, specifically the app\Console\Kernel.php file. This class is responsible for defining the schedule of Artisan commands that will be executed automatically by Laravel's task scheduler. Let's break down the key components of this code
app\Console\Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('guestpost:update-status')->daily();
$schedule->command('guestpost:update-status')->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
step4
- Open crontab -e in your linux server
/opt/lampp
/opt/lampp# crontab -e
command:-
* * * * * cd /opt/lampp/htdocs/wizbrand/wz-account-admin-ms && php artisan schedule:run >> /dev/null 2>&1
Summary
corn expression
Every 5 Minutes:
Every Day at 3 AM:
Every Monday at 8 PM
Every Last Day of the Month at Midnight:
every weekday (Monday to Friday) at noon
.
every hour at the 15th minute
every 2 hours
every Sunday and Wednesday at 4:00 AM
.
twice daily at 8:00 AM and 8:00 PM
on January 1st at midnight
Real time application of corn job
Sending Scheduled Emails
Data Backup
Cleanup Tasks
Cache Clearance
Updating Currency Exchange Rates
Generating Reports
Scheduled API Calls
Rotating Log Files
Automated Social Media Posts
Session Cleanup
Updating Search Index
Automated Notifications
Top comments (0)