QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads PHP Asynchronous Cron Job – Scheduling Tasks

PHP Asynchronous Cron Job – Scheduling Tasks

In this tutorial I will provide a method to run cron jobs in PHP that too asynchronous without affecting page load time. This doesn’t require to install any PHP extension or any other kinds of coding horrors.

Logic

We need two PHP files. The first file checks if scheduled time has passed or just occurred for a cron job. If its time to run the task then it starts a new asynchronous process to run the second PHP which is actually the cron callback.

Complete Code

Files are named: cron.php and schedule.php. cron.php contains the callback code and schedule.php should be runned every time user makes a request to the web server.

Here is the code for schedule.php

<?php
   
    if(get_option("cron_job_1") != null)
    {
                //run task every 1 hour.
        if(time() - get_option("cron_job_1") >= 3600)
        {
            $ch = curl_init();
                   
                        //send a request to the cron.php file so that its started in a new process asynchronous to the current process.
            curl_setopt($ch, CURLOPT_URL, 'http://yourdomain/cron.php');
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
                        //close connection after 1 millisecond. So that we can continue current script exection without effect page load time.
            curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
                        //some versions of curl don't support CURLOPT_TIMEOUT_MS so we have CURLOPT_TIMEOUT for them. Here we close connection after 1 second.
                        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
            curl_exec($ch);
            curl_close($ch);

            update_option("cron_job_1", time());
        }
    }
    else
    {
        update_option("cron_job_1", time());
    }

We have used PHP Options to store the last time in seconds when task was executed.

Here is the code for cron.php

<?php
    // Ignore user aborts
    ignore_user_abort(true);

    //allow the script to run forever. this is optional depending on how heavy is the task
    set_time_limit(0);

    //put the task code here.
Dec 29, 2014Narayan Prusty
How WordPress executes Async Cron without effecting page load timeTesting Intel XDK App on iOS Device using Ad Hoc
Comments: 8
  1. olivedev
    6 years ago

    I tried to manually schedule a cron job for PHP script that was running on my site, but it was really difficult to do for a beginner like me. I have since used my hosting providers platform, Cloudways, to do it automatically, which was extremely easy (an example: https://www.cloudways.com/blog/schedule-cron-jobs-in-php/).

    I wanted to ask if there is an easier way if I want to manually schedule tasks or using such platforms is the best alternative? Anyway thanks for this tutorial.

    ReplyCancel
  2. Ketav
    7 years ago

    I’m geting this error :
    Fatal error: Call to undefined function get_option() in /var/www/html/cron-job/schedule.php on line 4

    I’m trying this demo with core php code.

    ReplyCancel
  3. Mytaxe
    7 years ago

    its working fine

    ReplyCancel
  4. Ramon Figueroa
    7 years ago

    What I have to do if I want to run this as my cron job.(see below) How I place this in your cron.php file. Thanks for your help.

    0 * * * * /usr/bin/php /path/to/moodle/auth/db/cli/sync_users.php >dev/null

    ReplyCancel
  5. Pradeep
    7 years ago

    Sorry i just included it.it’s fetching data but

    i changed code as
    set_time_limit(60);

    //put the task code here.
    echo "hi pradeep";

    $file = fopen(“bulk_upload.csv”,”r”);

    while(! feof($file))
    {
    print_r(fgetcsv($file));
    }

    fclose($file);
    ?>

    and my csv records as

    1)pradeep varma Pradeep
    pradeep.penumatcha@cognizant.com password

    its displaying first record but i set time to 60 sec in between 60 sec i updated csv file added new record
    2) rakesh raju rakesh rakesh@cognizant.com password

    but after 60 sec its showing 1 record value only

    ReplyCancel
  6. Pradeep
    7 years ago

    i written code as you mentioned above but it’s throughing

    Fatal error: Call to undefined function get_option() in D:\xampp\htdocs\check\schedule.php on line 2

    please help me..

    ReplyCancel
    • Narayan Prusty
      7 years ago

      Please read the tutorial carefully. I have mentioned to first use the code from
      http://qnimate.com/storing-key-value-pairs-in-php-using-csv/

      ReplyCancel
  7. Jayasri
    7 years ago

    Thanks a ton! This helped me a lot. :)

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago 8 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Logic
  • Complete Code
Related Articles
  • Increase PHP Script Execution Time
  • How WordPress executes Async Cron without effecting page load time
  • Add Checkbox using WordPress Settings API
  • HTML5 Battery Status API with Code Example
  • Customizing Right Click Menu in HTML Page
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license