SlideShare a Scribd company logo
1 of 20
Download to read offline
Time Code: Automating
Tasks in WordPress with
WP-Cron
WordCamp Ottawa
Saturday, May 3, 2014
What is WP-Cron?
!
A task scheduler built into WordPress.
!
Named after the Unix Cron utility:
!
“The software utility cron is a time-based job scheduler in Unix-like
computer operating systems. People who set up and maintain software
environments use cron to schedule jobs (commands or shell scripts) to run
periodically at fixed times, dates, or intervals. It typically automates system
maintenance or administration—though its general-purpose nature makes
it useful for things like connecting to the Internet and downloading email at
regular intervals.[1] The name cron comes from the Greek word for time,
χρόνος chronos.”
!
- Wikipedia
!
!
Scheduling a Single Event
!
The wp_schedule_single_event() function is used to schedule an event to run once.
This could be used, for example, to send a follow up e-mail to a user at a scheduled
time after they register on your site:
!
add_action(‘user_register’, ‘schedule_followup_email’, 10, 1);
!
function schedule_followup_email($user_id) {
	 $userId = get_current_user_id();
	 wp_schedule_event(time() + 3600, ‘event_sendFollowupEmail’, array($user_id));
}
!
function sendWelcomeEmail($user_id) {
	 $user =get_user_by(‘id’, $user_id);
	 wp_mail($user->user_email, ‘Follow Up’, ‘Hope you’ve been enjoying our site’);
}
add_action(‘event_sendFollowupEmail’, ‘sendFollowupEmail’);
!
!
Scheduling Recurring Tasks
!
WP-Cron can run tasks at regular intervals
!
In the core:
!
• Checking if WordPress version is the most current
• Checking for theme and plugin updates
!
Functions:
!
• wp_get_schedule()
• wp_schedule_event()
• wp_get_next_scheduled()
• wp_clear_scheduled_hook()
• wp_unschedule_event()
!
Filter:
!
• cron_schedules
Schedules
Out of the box, WordPress can run recurring tasks:
!
• Daily (once every 24 hours)
• Twice Daily (every 12 hours)
• Hourly (every 60 minutes)
!
You can lookup supported schedules using wp_get_schedules()
!
array (size=3)
'hourly' =>
array (size=2)
'interval' => int 3600
'display' => string 'Once Hourly' (length=11)
'twicedaily' =>
array (size=2)
'interval' => int 43200
'display' => string 'Twice Daily' (length=11)
'daily' =>
array (size=2)
'interval' => int 86400
'display' => string 'Once Daily' (length=10)
Need Another Schedule?
You can create new schedules using the cron_schedules filter.
!
function add_new_cron_intervals($schedules) {
!
	 $schedules[‘weekly’] = array(
	 	 ‘interval’ => 604800,
	 	 ‘display’ => __(‘Once a week’)
	 );
!
	 $schedules[‘fourhours’] = array(
	 	 ‘interval’ => 60 * 60 * 4,
	 	 ‘display’ => __(‘Every four hours’)
	 );
!
	 return $schedules;
!
}
!
add_filter(‘cron_schedules’, ‘add_new_cron_intervals’);
Scheduling Recurring Tasks
!
!
!
function WeeklyMaintenanceTask_activate() {
	 // schedule the task

	 wp_schedule_event(time(), ‘weekly’, ‘WeeklyMaintenanceTask_run’);
}
register_activation_hook( __FILE__, 'WeeklyMaintenanceTask_activate' );
!
!
!
function WeeklyMaintenanceTask_run() {
	 // do maintenance task here
}
add_action(‘WeeklyMaintenanceTask_run’, ‘WeeklyMaintenanceTask_run’);
Cancelling Recurring Tasks
!
!
To clear all events related to a specified hook:
!
function WeeklyMaintenanceTask_deactivate() {
	 // clear scheduled tasks
	 wp_clear_scheduled_hook(‘WeeklyMaintenanceTask_run’);
}
register_deactivation_hook( __FILE__, 'WeeklyMaintenanceTask_deactivate' );
!
!
!
To clear only one event related to a specific hook:
(the difference - you need to know the timestamp of the event)
!
wp_unschedule_event(1399139100, ’WeeklyMaintenanceTask_run’);
Cancelling Recurring Tasks
!
!
When unscheduling/clearing events, the arguments you specified
during scheduling have to match!
!
wp_schedule_event(1399139100, ’MyHook’, array(1000));
!
!
When unscheduling/clearing events, the arguments you specified
during scheduling have to match!
!
wp_unschedule_event(1399139100, ’MyHook’);
Asynchronous Tasks
!
Perfect for long running tasks
!
Allows a user to continue working on your site
!
add_action(‘user_register’, ‘add_user_to_crm’, 10, 1);
!
function add_user_to_crm($user_id) {
	 $userId = get_current_user_id();
	 wp_schedule_event(time(), ‘event_addUserToCRM’, array($user_id));
}
!
function addUserToCRM($user_id) {
	 // insert slow running code here
}
add_action(‘addUserToCRM’, ‘addUserToCRM’);
Looking up a task
!
!
Perfect for avoiding duplicate events
!
wp_next_scheduled( $hook, $args );
!
This function returns the next scheduled cron event for the hook (and arguments)
selected.
!
If found, it will return the timestamp of the next event.
!
If there are no matches, it will return false.
Advantages of WP-Cron
!
!
It will work on all operating systems
!
!
!
!
!
!
!
!
!
No end user configuration required
Disadvantages of WP-Cron
!
Not a true Cron replacement
!
	 Only runs when someone visits your site
!
	 No visits = no jobs
!
!
!
Can use a lot of system resources on a busy site
!
!
Caching can cause events not to fire properly
Disabling WP-Cron
!
!
Add this to your wp-config.php file:
!
define(‘DISABLE_WP_CRON’, true);
Setting up Cron in cPanel
wget -q -O - http://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
Cron GUI by Simon Wheatley
Sample API Integration
Sample API Integration
!
Resources
!
Cron Functions in the WordPress Codex:
http://codex.wordpress.org/Function_Reference/wp_cron
!
Setting up a crontab file on the Unix server:
http://v1.corenominal.org/howto-setup-a-crontab-file/
!
EasyCron Web Service:
https://www.easycron.com/
!
Cron GUI WordPress Plugin:
http://wordpress.org/plugins/cron-view/
!
Epoch & Unix Time Conversion Tools:
http://www.epochconverter.com/
!
These slides:
http://www.5sen.se/wpcron
exit;
!
Thank you!
!
Questions?
!
shawn@fivesense.ca
!
Twitter: @shawnhooper
!
Slides:
http://5sen.se/wpcron
!

More Related Content

What's hot

اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیMohammad Reza Kamalifard
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wildBrainhub
 
Book integrated assignment
Book integrated assignmentBook integrated assignment
Book integrated assignmentAkash gupta
 
Java assgn
Java assgnJava assgn
Java assgnaa11bb11
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyondclintongormley
 
Synchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBSynchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBFrank Rousseau
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoSF
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1Ting-You Xu
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)振揚 陳
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queueAlex Eftimie
 
Montreal User Group - Cloning Cassandra
Montreal User Group - Cloning CassandraMontreal User Group - Cloning Cassandra
Montreal User Group - Cloning CassandraAdam Hutson
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.jsStarbuildr
 

What's hot (20)

اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
 
Book integrated assignment
Book integrated assignmentBook integrated assignment
Book integrated assignment
 
Sequelize
SequelizeSequelize
Sequelize
 
19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql
 
Java assgn
Java assgnJava assgn
Java assgn
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
Synchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBSynchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDB
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
 
Hadoop
HadoopHadoop
Hadoop
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
 
SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1
 
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp KrennJavantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
Montreal User Group - Cloning Cassandra
Montreal User Group - Cloning CassandraMontreal User Group - Cloning Cassandra
Montreal User Group - Cloning Cassandra
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.js
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 

Similar to Automating Tasks in WordPress with WP-Cron

Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014cklosowski
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
Automating your plugin with WP-Cron
Automating your plugin with WP-CronAutomating your plugin with WP-Cron
Automating your plugin with WP-CronDan Cannon
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascriptcrgwbr
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixInfluxData
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Coursecloudbase.io
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 

Similar to Automating Tasks in WordPress with WP-Cron (20)

Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Automating your plugin with WP-Cron
Automating your plugin with WP-CronAutomating your plugin with WP-Cron
Automating your plugin with WP-Cron
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Celery
CeleryCelery
Celery
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 

More from Shawn Hooper

Introduction to WordPress Security
Introduction to WordPress SecurityIntroduction to WordPress Security
Introduction to WordPress SecurityShawn Hooper
 
WP REST API: Actionable.co
WP REST API: Actionable.coWP REST API: Actionable.co
WP REST API: Actionable.coShawn Hooper
 
Database Considerations for SaaS Products
Database Considerations for SaaS ProductsDatabase Considerations for SaaS Products
Database Considerations for SaaS ProductsShawn Hooper
 
Payments Made Easy with Stripe
Payments Made Easy with StripePayments Made Easy with Stripe
Payments Made Easy with StripeShawn Hooper
 
WordPress Coding Standards & Best Practices
WordPress Coding Standards & Best PracticesWordPress Coding Standards & Best Practices
WordPress Coding Standards & Best PracticesShawn Hooper
 
Save Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command LineSave Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command LineShawn Hooper
 
Writing Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPressWriting Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPressShawn Hooper
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesShawn Hooper
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesShawn Hooper
 
WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015Shawn Hooper
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPressShawn Hooper
 
Writing Secure Code for WordPress
Writing Secure Code for WordPressWriting Secure Code for WordPress
Writing Secure Code for WordPressShawn Hooper
 
Manage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLIManage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLIShawn Hooper
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusShawn Hooper
 
WP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp MontrealWP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp MontrealShawn Hooper
 
WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015Shawn Hooper
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineShawn Hooper
 

More from Shawn Hooper (17)

Introduction to WordPress Security
Introduction to WordPress SecurityIntroduction to WordPress Security
Introduction to WordPress Security
 
WP REST API: Actionable.co
WP REST API: Actionable.coWP REST API: Actionable.co
WP REST API: Actionable.co
 
Database Considerations for SaaS Products
Database Considerations for SaaS ProductsDatabase Considerations for SaaS Products
Database Considerations for SaaS Products
 
Payments Made Easy with Stripe
Payments Made Easy with StripePayments Made Easy with Stripe
Payments Made Easy with Stripe
 
WordPress Coding Standards & Best Practices
WordPress Coding Standards & Best PracticesWordPress Coding Standards & Best Practices
WordPress Coding Standards & Best Practices
 
Save Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command LineSave Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command Line
 
Writing Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPressWriting Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPress
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
 
WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPress
 
Writing Secure Code for WordPress
Writing Secure Code for WordPressWriting Secure Code for WordPress
Writing Secure Code for WordPress
 
Manage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLIManage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLI
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp Columbus
 
WP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp MontrealWP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp Montreal
 
WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command Line
 

Recently uploaded

定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 

Recently uploaded (20)

定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 

Automating Tasks in WordPress with WP-Cron

  • 1. Time Code: Automating Tasks in WordPress with WP-Cron WordCamp Ottawa Saturday, May 3, 2014
  • 2. What is WP-Cron? ! A task scheduler built into WordPress. ! Named after the Unix Cron utility: ! “The software utility cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like connecting to the Internet and downloading email at regular intervals.[1] The name cron comes from the Greek word for time, χρόνος chronos.” ! - Wikipedia ! !
  • 3. Scheduling a Single Event ! The wp_schedule_single_event() function is used to schedule an event to run once. This could be used, for example, to send a follow up e-mail to a user at a scheduled time after they register on your site: ! add_action(‘user_register’, ‘schedule_followup_email’, 10, 1); ! function schedule_followup_email($user_id) { $userId = get_current_user_id(); wp_schedule_event(time() + 3600, ‘event_sendFollowupEmail’, array($user_id)); } ! function sendWelcomeEmail($user_id) { $user =get_user_by(‘id’, $user_id); wp_mail($user->user_email, ‘Follow Up’, ‘Hope you’ve been enjoying our site’); } add_action(‘event_sendFollowupEmail’, ‘sendFollowupEmail’); ! !
  • 4. Scheduling Recurring Tasks ! WP-Cron can run tasks at regular intervals ! In the core: ! • Checking if WordPress version is the most current • Checking for theme and plugin updates ! Functions: ! • wp_get_schedule() • wp_schedule_event() • wp_get_next_scheduled() • wp_clear_scheduled_hook() • wp_unschedule_event() ! Filter: ! • cron_schedules
  • 5. Schedules Out of the box, WordPress can run recurring tasks: ! • Daily (once every 24 hours) • Twice Daily (every 12 hours) • Hourly (every 60 minutes) ! You can lookup supported schedules using wp_get_schedules() ! array (size=3) 'hourly' => array (size=2) 'interval' => int 3600 'display' => string 'Once Hourly' (length=11) 'twicedaily' => array (size=2) 'interval' => int 43200 'display' => string 'Twice Daily' (length=11) 'daily' => array (size=2) 'interval' => int 86400 'display' => string 'Once Daily' (length=10)
  • 6. Need Another Schedule? You can create new schedules using the cron_schedules filter. ! function add_new_cron_intervals($schedules) { ! $schedules[‘weekly’] = array( ‘interval’ => 604800, ‘display’ => __(‘Once a week’) ); ! $schedules[‘fourhours’] = array( ‘interval’ => 60 * 60 * 4, ‘display’ => __(‘Every four hours’) ); ! return $schedules; ! } ! add_filter(‘cron_schedules’, ‘add_new_cron_intervals’);
  • 7. Scheduling Recurring Tasks ! ! ! function WeeklyMaintenanceTask_activate() { // schedule the task
 wp_schedule_event(time(), ‘weekly’, ‘WeeklyMaintenanceTask_run’); } register_activation_hook( __FILE__, 'WeeklyMaintenanceTask_activate' ); ! ! ! function WeeklyMaintenanceTask_run() { // do maintenance task here } add_action(‘WeeklyMaintenanceTask_run’, ‘WeeklyMaintenanceTask_run’);
  • 8. Cancelling Recurring Tasks ! ! To clear all events related to a specified hook: ! function WeeklyMaintenanceTask_deactivate() { // clear scheduled tasks wp_clear_scheduled_hook(‘WeeklyMaintenanceTask_run’); } register_deactivation_hook( __FILE__, 'WeeklyMaintenanceTask_deactivate' ); ! ! ! To clear only one event related to a specific hook: (the difference - you need to know the timestamp of the event) ! wp_unschedule_event(1399139100, ’WeeklyMaintenanceTask_run’);
  • 9. Cancelling Recurring Tasks ! ! When unscheduling/clearing events, the arguments you specified during scheduling have to match! ! wp_schedule_event(1399139100, ’MyHook’, array(1000)); ! ! When unscheduling/clearing events, the arguments you specified during scheduling have to match! ! wp_unschedule_event(1399139100, ’MyHook’);
  • 10. Asynchronous Tasks ! Perfect for long running tasks ! Allows a user to continue working on your site ! add_action(‘user_register’, ‘add_user_to_crm’, 10, 1); ! function add_user_to_crm($user_id) { $userId = get_current_user_id(); wp_schedule_event(time(), ‘event_addUserToCRM’, array($user_id)); } ! function addUserToCRM($user_id) { // insert slow running code here } add_action(‘addUserToCRM’, ‘addUserToCRM’);
  • 11. Looking up a task ! ! Perfect for avoiding duplicate events ! wp_next_scheduled( $hook, $args ); ! This function returns the next scheduled cron event for the hook (and arguments) selected. ! If found, it will return the timestamp of the next event. ! If there are no matches, it will return false.
  • 12. Advantages of WP-Cron ! ! It will work on all operating systems ! ! ! ! ! ! ! ! ! No end user configuration required
  • 13. Disadvantages of WP-Cron ! Not a true Cron replacement ! Only runs when someone visits your site ! No visits = no jobs ! ! ! Can use a lot of system resources on a busy site ! ! Caching can cause events not to fire properly
  • 14. Disabling WP-Cron ! ! Add this to your wp-config.php file: ! define(‘DISABLE_WP_CRON’, true);
  • 15. Setting up Cron in cPanel wget -q -O - http://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
  • 16. Cron GUI by Simon Wheatley
  • 19. Resources ! Cron Functions in the WordPress Codex: http://codex.wordpress.org/Function_Reference/wp_cron ! Setting up a crontab file on the Unix server: http://v1.corenominal.org/howto-setup-a-crontab-file/ ! EasyCron Web Service: https://www.easycron.com/ ! Cron GUI WordPress Plugin: http://wordpress.org/plugins/cron-view/ ! Epoch & Unix Time Conversion Tools: http://www.epochconverter.com/ ! These slides: http://www.5sen.se/wpcron