Tagged: cron Toggle Comment Threads | Keyboard Shortcuts

  • Jay Versluis 5:38 pm on January 17, 2014 Permalink | Reply
    Tags: cron,   

    Categories: WordPress ( 137 )

    How to create a Cron Job in WordPress: Teach your plugin to do something automatically 

    pencil-iconCreating a recurring automatic function in WordPress used to be one of the most difficult things for me to understand. Several articles out there explain how to do it, yet I always forgot the concepts when the next cron job job came along. Right now it’s in my head, and that’s the time when I like to write things down for “next time”. I hope these notes will help you in your own development.

    Setting up a Cron Job in WordPress involves the following items:

    1. a scheduled event, i.e. something that WordPress will execute repeatedly
    2. our own function with code to execute (we’ll hook it into the above)
    3. the event needs to be run when WordPress loads
    4. the event needs to be unscheduled upon plugin deactivation

    So we’re hooking into WordPress, which gives us a new “timed hook” into which we hook our own function. No wonder this is a complex subject.

    In addition, WordPress only offers three schedules, so we’ll also look into how to add our own intervals. Let’s get started.

    Creating our Scheduled Event

    First we’ll create a function that will schedule our event. Mine is called “mycronjob” and it will run once every day. All this code can go into your plugin’s main file, outside the main function:

    // create a scheduled event (if it does not exist already)
    function cronstarter_activation() {
    	if( !wp_next_scheduled( 'mycronjob' ) ) {  
    	   wp_schedule_event( time(), 'daily', 'mycronjob' );  
    	}
    }
    // and make sure it's called whenever WordPress loads
    add_action('wp', 'cronstarter_activation');
    

    At the same time we want to make sure it’s unscheduled when the plugin is deactivated:

    // unschedule event upon plugin deactivation
    function cronstarter_deactivate() {	
    	// find out when the last event was scheduled
    	$timestamp = wp_next_scheduled ('mycronjob');
    	// unschedule previous event if any
    	wp_unschedule_event ($timestamp, 'mycronjob');
    } 
    register_deactivation_hook (__FILE__, 'cronstarter_deactivate');
    

    Now we have a hook called “mycronjob” which will be called once every day. Let’s add our own function to it:

    Adding your Repeat Function

    To prove that this is working we’ll send an email in this example – this is just a placeholder for your own code you’d like to run on a recurring basis:

    // here's the function we'd like to call with our cron job
    function my_repeat_function() {
    	
    	// do here what needs to be done automatically as per your schedule
    	// in this example we're sending an email
    	
    	// components for our email
    	$recepients = 'you@example.com';
    	$subject = 'Hello from your Cron Job';
    	$message = 'This is a test mail sent by WordPress automatically as per your schedule.';
    	
    	// let's send it 
    	mail($recepients, $subject, $message);
    }
    
    // hook that function onto our scheduled event:
    add_action ('mycronjob', 'my_repeat_function'); 
    

    Note how we’re adding the function to your specified event in the last line of code.

    In all likelihood – and definitely for testing purposes – you may not be able to sit and wait an entire day for this email to be sent. Hence we need a more immediate schedule. Let’s tackle that next.

    Creating Custom Intervals

    By default, WordPress provides the following time intervals you can use:

    • daily
    • twicedaily
    • hourly

    You can add your own intervals too: here’s an example in which we’re creating an interval that runs once every minute:

    // add custom interval
    function cron_add_minute( $schedules ) {
    	// Adds once every minute to the existing schedules.
        $schedules['everyminute'] = array(
    	    'interval' => 60,
    	    'display' => __( 'Once Every Minute' )
        );
        return $schedules;
    }
    add_filter( 'cron_schedules', 'cron_add_minute' );
    

    We’re adding an array called “everyminute” to the existing default intervals. You specify this in seconds and give it a display name that describes what it does.

    To use this interval you need to create your scheduled event with the array name. To stick with the above example, here’s how we’d create our “mycronjob” event once every minute:

    // create a scheduled event (if it does not exist already)
    function cronstarter_activation() {
    	if( !wp_next_scheduled( 'mycronjob' ) ) {  
    	   wp_schedule_event( time(), 'everyminute', 'mycronjob' );  
    	}
    }
    // and make sure it's called whenever WordPress loads
    add_action('wp', 'cronstarter_activation');
    

    The unschedule function remains the same as above.

    Checking and Testing your Scheduled Events

    Before you go on a coding spree you probably want to know if this event is actually happening as planned. I like to do this in two ways.

    Setup something tangible like the email function above and set the schedule to something like once every minute. Then refresh the front page of your WordPress test instance once or twice and watch your inbox. You should receive emails more or less once a minute, if you keep refreshing the front page (not the admin page). If this works, then you’re good to go.

    Another way to check if your event is recognised by WordPress is a lovely plugin by Simon Wheatly called Cron View:

    http://wordpress.org/plugins/cron-view/

    Once activated it will show you which events are scheduled by WordPress. Let me show you how helpful this is. The first screenshot shows a vanilla WordPress installation with its own scheduled events. “mycronjob” is nowhere to be seen (nor should it at this point):

    Screen Shot 2014-01-17 at 17.11.57

    Now we’ll activate my own cron starter plugin and refresh the front page. We’ll also refresh the What’s In Cron page to see this:

    Screen Shot 2014-01-17 at 17.12.34

    Just what the doctor ordered: “mycronjob” is scheduled to run in the next minute, and at the top of the screen I can see my custom schedule that have been added (Once every Minute). You can see this menu under Tools – What’s In Cron.

    Thanks, Simon!

    Final Thoughts

    WordPress Scheduled Events are not “real” Cron Jobs, like the UNIX Cron Tab. The difference is that a “real” cron job would be reliably called by the server clock. Scheduled Events on the other hand are determined by how long ago the last event happened. If the time interval between “last run” and “right now” is larger than specified, the event fires.

    This in turn relies on visitor traffic. On low or no-traffic websites like your test environment this means your event may not fire as expected. You can help this along by refreshing your front page.

    Also note that traffic kicking off scheduled events can be disabled in wp-config.php by adding the following line:

    define('DISABLE_WP_CRON', 'true');
    

    This is often done so that a “real” cron job can call the wp-cron.php file in exactly specified intervals (we’ll deal with this in another article). It’s not the default setting, but definitely something to check if your events are not working as expected.

    Demo Project

    I have created a demo project on GitHub that implements the above and works out of the box:

    Happy Automation!





     
    • Bill 11:43 pm on January 17, 2014 Permalink | Reply

      Thanks for the article.
      Need a real cron, but you host doesn’t provide it, you can consider using a wordpress plugin: http://www.wordpress.org/plugins/easycron/ .

    • Rob 12:26 pm on December 20, 2014 Permalink | Reply

      How can I call the crown on a specific day? f.e. send a mail every Friday
      -Rob

      • Jay Versluis 10:01 pm on December 20, 2014 Permalink | Reply

        Hi Rob,

        As far as I know there’s no easy way to do it that specifically via WordPress. The closest you can do is create your own “once every week” schedule (604.800 seconds) and activate the plugin on a Friday.

        If you need more accuracy over a certain function you can call a specific PHP file via cron job once every Friday and not hook into WordPress cron.

        Hope this helps.

    • reedyseth 3:53 pm on April 9, 2015 Permalink | Reply

      Hey the comment

      // and make sure it’s called whenever WordPress loads

      on the action

      add_action (‘mycronjob’, ‘my_repeat_function’);

      Helped me to debug a code that I was stuck in. Now my function gets call every time that is needed.

    • shreyavasa 5:14 am on November 27, 2015 Permalink | Reply

      Hi,
      I am using wordpress 4.3.1 but unable to call ‘my_repeat_function’.
      Any help ??

      • Jay Versluis 12:24 am on November 30, 2015 Permalink | Reply

        Without seeing your code I’m afraid I can’t help you much.

  • Jay Versluis 3:47 pm on September 28, 2012 Permalink | Reply
    Tags: backups, cron, Plesk 11, scheduled   

    Categories: Plesk ( 70 )

    How to bring back Scheduled Backups in Plesk 11 

    For those of you who hadn’t noticed, automatic scheduled backups are no longer working in Plesk 11 with some distributions. It’s not just you, and it’s not just your configuration. It’s a known issue according to this forum thread.

    Lucky for us there’s a simple script which can bring this ever so important functionality back. Why Parallels is not addressing this with a Micro Update is beyond me (we’re already at 11.0.9 MU15 and it’s September 2012 at the time of writing).

    In this article I’ll show you how to install the script step by step. I assume you’re logged onto your system as root and know your way around the command line.

    (More …)





     
    • Jack 10:31 am on October 4, 2012 Permalink | Reply

      I have tried implementing this fix and it all works fine until I execute the file. It doesn’t show any error or success message and nothing shows up in the cron tab so it still isn’t working…

      Any suggestions?

      Jack

      • Jay Versluis 11:31 am on October 4, 2012 Permalink | Reply

        Hi Jack,

        Once you run the script it installs itself into Plesk, there’s nothing added in the cron tab, nor will there be a success message. Try scheduling a backup in Plesk as you normally would, not via the command line. Then see if Plesk has created it for you as you’d expect.

        • Jack 4:39 pm on October 4, 2012 Permalink | Reply

          Hi,

          Yeah I realised afterwards, I was expecting it to show on the cron tab as a scheduled task but it doesn’t. It does work though, thanks for posting you;re a life saver!

          Cheers,

          Jack

    • Jay Versluis 9:47 am on November 4, 2012 Permalink | Reply

      UPDATE:
      Allegedly the issue was fixed with MU 20, however many of us believe it has not been sufficiently addressed. Looks like even though scheduled backups are created again, but the dump files never get copied to the FTP repositories. Not good!

      Log messages from those backup tasks are given as “Success”. Looks like the issue affects both fresh installations as well as upgrades. I’ve submitted a ticket to the support team and will keep you posted on updates here.

      • Bjoern Strausmann 3:14 pm on November 13, 2012 Permalink | Reply

        Hello,

        have you any response from the parallels support for you ticket ?

        Regards,

        Björn

        • Jay Versluis 1:47 pm on November 18, 2012 Permalink | Reply

          Hi Björn,

          sadly not – but that was entirely my fault. I’ve just moved countries (UK to US) and haven’t yet followed up with them. I must admit it’s been 14 days so they’ve probably closed my ticket by now. As soon as I’m settled I’ll try again.

          Out of interest, what’s your configuration that’s not backing up? I’ve got this mainly on CentOS 5.8, not on 6.3. And affected systems have been upgraded, fresh installs seem to work fine.

    • tony 4:27 pm on January 7, 2013 Permalink | Reply

      Have you gotten support/updates to this?

      YIKES: I’ve just found out that manual backups are transferred to the FTP repo, but scheduled backups are not! It’s a known issue, we’re all waiting for a solution there…

      • Jay Versluis 3:48 am on January 8, 2013 Permalink | Reply

        Hi Tony,

        sadly I haven’t – the plot thickened a bit: I have reason to believe that it was my FTP repository that kept timing out for any amount of data over and above 2.6GB. Not sure why, but smaller backups have started to work after adding this script to my setup. I can also confirm that single domain backups work fine when automated, and that the server configuration (being much smaller) also gets backed up on schedule.

        BUT… I used to be able to make backups server-wide of 30GB and more via FTP. I’m still puzzled as to what’s changed. Speed into my FTP server? Who knows. I’ll keep digging. In the meantime, if you have any clues please let me know.

    • Matt Caswell 6:32 pm on January 9, 2013 Permalink | Reply

      I’m running Plesk 11.0.9 #32 and I can use scheduled FTP backups on small files, but I have a domain with 15gb and it always fails. I looked into the logs and it says that there isn’t enough disk space. I know Plesk saves the file locally and then FTP’s it over to my backup.. what I can’t figure out is where it saves the file and how can I change where it saves it so I can point it to a drive that has over 100GB available. I don’t know if this is a bug in Plesk still or if I just need to change configs.

      • Jay Versluis 6:48 pm on January 9, 2013 Permalink | Reply

        Hi Matt,

        backups in Plesk are stored in /var/lib/psa/dumps. They look different than what gets saved via FTP though, which I assume is just a zipped version of a collection of files. Old backups are hiding in that directory, it’s a good idea to keep an eye on it and clear it out occasionally. I’ve written it down here – I could never remember this either: https://wpguru.co.uk/2009/12/where-are-the-backup-files-in-plesk/

        How to change this path I don’t know I’m afraid. The Parallels Forum is probably your best bet – let me know if you find out.

    • Matt Caswell 6:32 pm on January 9, 2013 Permalink | Reply

      by the way.. Thank you for your great info on the script!

    • Bryan Williams 9:16 am on April 20, 2016 Permalink | Reply

      Can you provide details on what this script does?

  • Jay Versluis 6:34 pm on December 29, 2011 Permalink | Reply
    Tags: , cron, ,   

    Categories: Linux, PHP ( 96 )

    What’s the full path to php in CentOS? 

    The path to PHP is

    /usr/bin/php

    This is good to know if you need to setup a cron job which triggers a PHP file. Calling it from a web browser directly is not a problem, but if you have to call it from the command line or as a scheduled task you need to call it with

    /usr/bin/php yourfile.php

    You can also use wget or cURL but that’s often not reliable.

    If your PHP file gives you an output (usually to the browser screen), your server will send you an email. If you;d rather this didn’t happen, direct it to nowhere like so:

    /usr/bin/php yourfile.php > /dev/null 2>&1





     
  • Jay Versluis 10:52 am on February 12, 2009 Permalink | Reply
    Tags: , , cron, , , ,   

    Categories: Linux ( 96 )

    How to setup a Cron Job in Linux and Plesk 

    Wouldn’t it be great if something could be triggered even when you’re not around? Say once an hour, once a day, once a week or whenever you like in predetermined intervals?

    Then you want to do this with what’s known as a Cron Job, or Scheduled Task.

    Unfortunately, this is a bit beyond what WordPress can do, and it means getting down to the nitty gritty of the internal workings  of your server (after all, that’s where WordPress lives). Bear with me here, I’ll try my best to explain and show solutions.

    I’m using a Cron Job with Manu Flury’s excellent Photo Q Plugin. It posts one of my pictures over at http://www.versluis.com every so many hours. But for this to work properly, both the WordPress Plugin and my (Linux) server need to be setup correctly.

    Some WordPress Plugins (like Rob Felty’s Postie or Charles Johnson’s Feed WordPress) have similar functionality built in, but they rely on a visitor coming to your site at predetermined intervals. That’s not something you can control really. In most cases it works reliable enough for these plugins to work, however many others just don’t have that functionality, or require more accurate control. That’s where your Cron Job comes in.

    So what on earth is a Cron Job?

    In a nutshell, it’s a task that’s triggered at predetermined intervals. But it’s a bit like sitting in front of a Linux Prompt on your SSH connection, and all you have at your displosal is a keyboard with a black screen and white text to type in. What’s worse, your server doesn’t speak “WordPress”, or PHP for that matter. So all you can do really is to give him Linux commands.

    In all likelyhood, you probably want to call a PHP file so that WordPress does something for you (such as check if it’s time for a new post, or maybe a database backup). And you can’t just tell Linux to go to that file, becasue it wouldn’t know what to do with it. I’ve tried this without success many times over (they nearly put me in a mental institution, seriously… I can assure you I’m much better now though).

    So you need to find a command that calls your PHP file as if it were a browser. Lucky for us, the command “wget” will do the trick.

    Wget is really designed for downloading a file to your server, but it’ll work fine for triggering a PHP file, just as a browser would do. The command for calling the Photo Q file for example looks like this:

    /usr/bin/wget -O - -q -t 1 http://www.yourdomain.com/wimpq-cronpost.php

    Confused? Don’t be! Let me explain:

    • “/usr/bin/wget” tells the server where the wget command is (it’s a path to a file if you hadn’t guessed)
    • “-O – -q -t -1” are some random parameters, let’s not concern ourselves with those right now (if you really want to find out, type in “wget –help” at your SSH prompt)
    • http://www.yourdomain.com/wimpq-cronpost.php” is the actual file you want to call, just like what you’d type into your browser

    Now that we know how to call upon a PHP file from our command prompt, we need to tell our server to do this without us being there, and at what times he needs to do this. He’ll be more than happy to oblige, after all, that’s what he was designed to do.

    How to setup a Cron Job in Plesk

    I’ll focus on how to do this in Plesk 9 here, which refers to it as Scheduled Tasks (earlier versions of Plesk call it Crontab).

    Here’s how you get there:

    • from the main menu on the left, select HOME
    • select DOMAINS
    • select the DOMAIN you want to run this task on
    • under Additional Tools, select SCHEDULED TASKS
    • choose the SYSTEM USER you would like this task to be run as
    • select SCHEDULE NEW TASK

    OK, this was complicated enough to figure out – now comes the part nobody ever really talks about. It’s hard to explain, so please bear with me if I’m not making a whole lot of sense at first. In essence, you’re telling your server WHEN to do something, followed by WHAT to do.

    • Each field requires an entry. Don’t leave them blank.
    • The first tick box is to “switch on” the task. That’s what you want, unless you want to suspend the task. Tick it for now.
    • Now tell your server WHEN your task shall be run.
    • a “*” (i.e. star or asterisk) means “every”. So a star in minute would run the task “every minute”, likewise for hours and days of the month
    • You can also create the command “*/5” if you want your task run every 5 hours, every 5 days, every 5 minutes – you get the drift
    • Alternatively, put in the specific date (i.e. “Monday” and “17” for Monday at 5pm)

    After all that, you’re left with one last line, which is the actual command or task you’d like to be run.

    Like I explained above, for a PHP file to be called, use the wget command like so:

    /usr/bin/wget -O - -q -t 1 http://www.yourdomain.com/wimpq-cronpost.php

    Obviously change the path to your file, including “http://”

    Click OK on the bottom and your task should be setup. No need to reboot anything.

    If at any time you feel you want to amend the task, you can do so by just modifying the parameters, or uncheck the “run task” tickbox to suspend the task completely.

    If you want to know even MORE about Cron Jobs, check this out:

    http://www.hingham-ma.com/sendstudionx/admin/resources/tutorials/cron_intro.html

    Good Luck, and have fun 😉





     
    • Brian 5:05 pm on February 14, 2011 Permalink | Reply

      This post was not very helpful. The title is “How to setup a Cron Job *in WordPress*”. This does not seem to be any different than setting up a cron for any other PHP script, other than you’re using wget, rather than PHP directly. The title leads you to believe you explain how to setup your .php file to use pieces of WordPress and $wpdb, but your post contains no such information.

      For anyone looking to do this, all you need to do is include the /wp-load.php file in your cron file and you will have you DB Config and WPDB Class.

      • Jay Versluis 5:46 pm on February 14, 2011 Permalink | Reply

        Hi Brian,

        I’m very sorry you didn’t find the info useful – and reading back over the article I can understand why: the title is indeed misleading. I have changed it to “How to setup a cron job” because that’s what it’s about – nothing to do with WordPress.

        Thanks for contributing the wp-load.php tip – I’ll check it out!

        • Sandy Nerja 6:45 pm on December 6, 2011 Permalink | Reply

          My website takes xml feeds from local estate agents, and imports their properties to display on my holiday accommodation website. The whole thing is written in wordpress, and up to now I have been manually triggering the script that imports the rental properties from the agents sites.

          Finally I have got round to automating the process and the missing link was the wp-load.php. Use it like this at the start of your script:

          require( ‘wp-load.php’ );

          This assumes your script is in the same folder as wp-load and from then on your script acts like it has been called from WordPress.

          I hope this is useful to someone else.

    • Pranny 10:15 pm on August 8, 2011 Permalink | Reply

      That’s really helpful for me !

    • Jonas 6:43 pm on November 10, 2011 Permalink | Reply

      Thanks for the article!

      How do you prevent from someone triggering the cron job by just visiting http://www.yourdomain.com/wimpq-cronpost.php ? Is there a way to make sure only the server can trigger the task?

      • Jay Versluis 3:33 pm on November 17, 2011 Permalink | Reply

        Hmmm… good question. Since this is a public file it needs to be triggered via http. However, if you move the wimpq-cronpost.php file to somewhere above public level you should be able to trigger it via PHP from the command line queue for example – but I don’t know what the implications of the PhotoQ Plugin will be. I believe the developer said it needs to be in the root folder.

        I suppose it doesn’t really matter if you (or someone else) triggers the file more often than it needs to be called since the actual time in between automatic posts is determined via the Plugin Settings. Say you call this file every 5 minutes, but you setup PhotoQ to only post a new picture once every hour, then it will only post it once every hour.

    • Roy M J 8:37 am on January 31, 2012 Permalink | Reply

      Hi,

      I am using a plesk panel with godaddy and i cannot find how to set up a cron job. What i would like to know is whether wordpress has any plugins or set-up a cron job.

      Many thanks

      Roy M J

      • Jay Versluis 10:43 am on January 31, 2012 Permalink | Reply

        Hi Roy,

        WordPress has a built-in cron function which plugin developers can use. This however relies on somebody visiting your site regularly so it can appear to be unreliable. They do a good job for internal functions, but you can’t easily trigger a script without writing a plugin.

        Plesk calls Cron Jobs “Scheduled Tasks”, you can find those under Tools and Settings (in Hosting Provider View) or under Websites and Domains – Advanced (in Power User View).

    • taipres 2:27 am on February 14, 2012 Permalink | Reply

      The way you prevent a user from triggering your cron php script early is simply ignore all IP’s/Hosts besides your servers.

      if (getenv(HTTP_X_FORWARDED_FOR)) {
      $ipaddress = getenv(HTTP_X_FORWARDED_FOR);
      } else {
      $ipaddress = getenv(REMOTE_ADDR); }

      if($ipaddress != “1.1.1.1”){
      //do nothing
      }

      I use it on my site http://cheapvpsdeals.info for various things.

      • Jay Versluis 4:22 pm on February 16, 2012 Permalink | Reply

        Superb tip, thank you so much for sharing this. It’ll certainly come in handy 😉

    • nSathees 9:24 pm on February 20, 2012 Permalink | Reply

      @Brian: Hammered the nail on the head! Thanks for that wp_load point! That’s all I needed to know.

    • nSathees 9:33 pm on February 20, 2012 Permalink | Reply

      just a thought!

      what if I setup a php file with
      header(Location:’http://example.com’) which is my WordPress setup
      and trigger that php page via corn job.

      Would that work?

    • David Feldt 7:47 pm on September 5, 2012 Permalink | Reply

      Very useful – thanks!

  • Jay Versluis 4:20 pm on February 9, 2009 Permalink | Reply
    Tags: , , cron, , , , ,   

    Categories: Domains and Hosting ( 4 )

    What is a CRON Job? 

    Although I’ve been dealing with webshoting and webdesign since 1995, it took me a whilw to figure this one out. If you’re used to shared shosting packages, it’s likely that you’ve never come in contact with this. Hence, this article is aimed at people who don’t know what it is.

    As explained in Wikipedia:

    Cron is the name of a program that enables unix users to execute commands or scripts (groups of commands) automatically at a specified time/date. It is normally used for sys admin commands, like makewhatis, which builds a search database for the man -k command, or for running a backup script, but can be used for anything. A common use for it today is connecting to the internet and downloading your email.

    So a cronjob is a scheduled action, which is executed by and on your web server. WordPress itself doesn’t do this for you. It’s like having a monkey sitting at a command prompt, typing something in every minute/hour/day – in regular intervals – you get the drift.

    In order to setup this automatic execution, you need to be in control of your own dedicated or virtual server. If you’re on shared a shared hosting plain, you can ask your provider to setup a cron job for you. Just tell them “I want (this particular file in this particular directory) executed every Thursday evening at 9”. Otherwise, use your own administrative panel (like Plesk or Webmin) to set this up.

    Want to know how? Read the following article: How to setup a Cron Job?





     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel