Wrangling WP_Cron - WordCamp Grand Rapids 2014

@cklosowski cklosows
Wrangling WP_Cron Scheduling Your Tasks the WordPress Way
Chris Klosowski
• Plugin Developer (WP-Push.com, PostPromoterPro.com,
GitHub, WordPress.org)
• Contributing Developer and Support Tech for Easy Digital
Downloads
• Hang out with my Wife and Kid
@cklosowski cklosows
WP_Cron
A tool to replace a tool
What is “Cron”
• A time-based job scheduler in Unix-like computer
operating systems.
• Used to schedule jobs (commands or shell scripts) to run
periodically at fixed times, dates, or intervals.
• Cleanup, populate data into cache, etc.
WP_Cron
The platform-agnostic task
scheduler
WP_Cron vs Cron
• Works on Windows based systems
• Works when you don’t have access to cron
• Easily allows access to the WordPress core
• “Reliably” available to Theme and Plugin developers
Basic Usage	
<?php
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
Simple Right?
Sort Of
Some Caveats
$timestamp
• The first time you want this item to run
• UNIX Timestamp format
• Always in UTC (not localized timezone)
• Use time(); as it uses GMT for right now
• No Default
get_option( 'gmt_offset' );
$recurrence
• The name of the schedule value
• hourly
• twicedaily
• daily
• Using cron_schedules filter, you can add your own recurrences.
• Not a timestamp, but a string that references a timestamp
• Number of seconds between occurrences
$hook
• Essentially does a do_action() when it runs. You would
then attach a function to this hook you’re creating.
• Possible issue on some systems where the hook must
not contain underscores or uppercase characters. (Have
not seen this myself)
$args
• Optional array of data to pass through the hook
• Great for when doing post or page specific crons
• Used later when doing lookups for scheduled crons.
• Must be an indexed array (no numeric keys)
// Be Kind, Rewind
register_deactivation_hook( __FILE__, 'ck_deactivation' );
function ck_deactivation() {
wp_clear_scheduled_hook( 'ck_hourly_event_hook' );
}
<?php
register_activation_hook( __FILE__, 'ck_activation' );
!
function ck_activation() {
wp_schedule_event( time(), 'hourly', 'ck_hourly_event_hook' );
}
!
add_action( 'ck_hourly_event_hook', 'ck_do_this_hourly' );
function ck_do_this_hourly() {
// do something every hour
}
<?php
// Situation of single event
$args = array( 'post_id' => 42, 'service' => 'twitter' );
wp_schedule_single_event( time(), 'ck_single_event', $args );
!
!
// Clear with same hook and EXACT same args
$args2 = array( 'post_id' => 42, 'service' => 'twitter' );
wp_clear_scheduled_hook( 'ck_single_event', $args2 );
Why Not WP_Cron?	
Not all unicorns and rainbows
Because WP_Cron _______________
• Why WP Cron Sucks

http://www.lucasrolff.com/wordpress/why-wp-cron-sucks/
• Disabling WP-Cron in WordPress

http://www.limecanvas.com/disabling-wp-cron-in-wordpress/
• Understanding WP Cron, and why I don’t use it

http://chrislema.com/understanding-wp-cron/





…I could go on…
Low Traffic Sites
• WP_Cron is based off traffic

• No visits, no cron

• Unreliable for time specific
tasks
High Traffic Sites
• Possibility of many concurrent
cron events.

• Expensive cron events can
cause load issues.

• If needing EXACT times, still
not 100%
Race Conditions
• Identified by the same
scheduled task running twice,
at the same time.

• Due to PHP threads, they
aren’t aware of each other
Missed Tasks
• They will run.

• Scenario

• Tasks scheduled 8a and 9a.

• No cron run until 9:15a

• Both tasks will run at 9:15a

• Be aware of this when:

• Pushing to Web Services

• APIs
How to Wrangle WP_Cron
• 3rd party ping service (Pingdom)
• Setup an actual cron if available

http://domain.com/wp-cron.php?doing_wp_cron=1



• Limit threads with DB or file locks
• Know what crons are scheduled, and what they do
define('DISABLE_WP_CRON', true);
@cklosowski cklosows
Questions? Scheduling Your Tasks the WordPress Way
1 of 22

Recommended

Automating your plugin with WP-Cron by
Automating your plugin with WP-CronAutomating your plugin with WP-Cron
Automating your plugin with WP-CronDan Cannon
6K views20 slides
"Service Worker: Let Your Web App Feel Like a Native " by
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
8.7K views42 slides
Javascript Promises/Q Library by
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
28.8K views28 slides
JavaScript Engines and Event Loop by
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
358 views28 slides
Embuk internals by
Embuk internalsEmbuk internals
Embuk internalsSadayuki Furuhashi
3.2K views9 slides
Embulk - 進化するバルクデータローダ by
Embulk - 進化するバルクデータローダEmbulk - 進化するバルクデータローダ
Embulk - 進化するバルクデータローダSadayuki Furuhashi
4.9K views35 slides

More Related Content

What's hot

Automating OSD and Post-OSD Configuration with Powershell and Orchestrator by
Automating OSD and Post-OSD Configuration with Powershell and OrchestratorAutomating OSD and Post-OSD Configuration with Powershell and Orchestrator
Automating OSD and Post-OSD Configuration with Powershell and OrchestratorDigicomp Academy AG
1.6K views27 slides
Recent Updates at Embulk Meetup #3 by
Recent Updates at Embulk Meetup #3Recent Updates at Embulk Meetup #3
Recent Updates at Embulk Meetup #3Muga Nishizawa
855 views28 slides
API Days Paris - Automatic Testing of (RESTful) API Documentation by
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationRouven Weßling
438 views26 slides
Callbacks and control flow in Node js by
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
2K views18 slides
Using Embulk at Treasure Data by
Using Embulk at Treasure DataUsing Embulk at Treasure Data
Using Embulk at Treasure DataMuga Nishizawa
1.6K views29 slides
Raymond Kuiper - Working the API like a Unix Pro by
Raymond Kuiper - Working the API like a Unix ProRaymond Kuiper - Working the API like a Unix Pro
Raymond Kuiper - Working the API like a Unix ProZabbix
3.2K views35 slides

What's hot(20)

Automating OSD and Post-OSD Configuration with Powershell and Orchestrator by Digicomp Academy AG
Automating OSD and Post-OSD Configuration with Powershell and OrchestratorAutomating OSD and Post-OSD Configuration with Powershell and Orchestrator
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
Digicomp Academy AG1.6K views
Recent Updates at Embulk Meetup #3 by Muga Nishizawa
Recent Updates at Embulk Meetup #3Recent Updates at Embulk Meetup #3
Recent Updates at Embulk Meetup #3
Muga Nishizawa855 views
API Days Paris - Automatic Testing of (RESTful) API Documentation by Rouven Weßling
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling438 views
Callbacks and control flow in Node js by Thomas Roch
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
Thomas Roch2K views
Using Embulk at Treasure Data by Muga Nishizawa
Using Embulk at Treasure DataUsing Embulk at Treasure Data
Using Embulk at Treasure Data
Muga Nishizawa1.6K views
Raymond Kuiper - Working the API like a Unix Pro by Zabbix
Raymond Kuiper - Working the API like a Unix ProRaymond Kuiper - Working the API like a Unix Pro
Raymond Kuiper - Working the API like a Unix Pro
Zabbix3.2K views
Redux. From twitter hype to production by FDConf
Redux. From twitter hype to productionRedux. From twitter hype to production
Redux. From twitter hype to production
FDConf8.8K views
Service worker: discover the next web game changer by Sandro Paganotti
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
Sandro Paganotti1.6K views
Data integration with embulk by Teguh Nugraha
Data integration with embulkData integration with embulk
Data integration with embulk
Teguh Nugraha1.2K views
Scalable Angular 2 Application Architecture by FDConf
Scalable Angular 2 Application ArchitectureScalable Angular 2 Application Architecture
Scalable Angular 2 Application Architecture
FDConf9.4K views
Cross Domain Web
Mashups with JQuery and Google App Engine by Andy McKay
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay3.7K views
JS Chicago Meetup 2/23/16 - Redux & Routes by Nick Dreckshage
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & Routes
Nick Dreckshage600 views
Fighting Against Chaotically Separated Values with Embulk by Sadayuki Furuhashi
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
Sadayuki Furuhashi2.1K views
«От экспериментов с инфраструктурой до внедрения в продакшен»​ by FDConf
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf5.3K views
Coolblue - Behind the Scenes Continuous Integration & Deployment by Matthew Hodgkins
Coolblue - Behind the Scenes Continuous Integration & DeploymentCoolblue - Behind the Scenes Continuous Integration & Deployment
Coolblue - Behind the Scenes Continuous Integration & Deployment
Matthew Hodgkins1.2K views
V2 and beyond by jimi-c
V2 and beyondV2 and beyond
V2 and beyond
jimi-c13.9K views
Background Jobs with Resque by homanj
Background Jobs with ResqueBackground Jobs with Resque
Background Jobs with Resque
homanj6.6K views

Similar to Wrangling WP_Cron - WordCamp Grand Rapids 2014

Time Code: Automating Tasks in WordPress with WP-Cron by
Time Code: Automating Tasks in WordPress with WP-CronTime Code: Automating Tasks in WordPress with WP-Cron
Time Code: Automating Tasks in WordPress with WP-CronShawn Hooper
2.6K views20 slides
FireWorks workflow software by
FireWorks workflow softwareFireWorks workflow software
FireWorks workflow softwareAnubhav Jain
12.6K views39 slides
Supercharging WordPress Development - Wordcamp Brighton 2019 by
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
612 views64 slides
Integration-Monday-Stateful-Programming-Models-Serverless-Functions by
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsBizTalk360
244 views34 slides
Performance patterns by
Performance patternsPerformance patterns
Performance patternsStoyan Stefanov
4.1K views82 slides
Make BDD great again by
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
84 views32 slides

Similar to Wrangling WP_Cron - WordCamp Grand Rapids 2014(20)

Time Code: Automating Tasks in WordPress with WP-Cron by Shawn Hooper
Time Code: Automating Tasks in WordPress with WP-CronTime Code: Automating Tasks in WordPress with WP-Cron
Time Code: Automating Tasks in WordPress with WP-Cron
Shawn Hooper2.6K views
FireWorks workflow software by Anubhav Jain
FireWorks workflow softwareFireWorks workflow software
FireWorks workflow software
Anubhav Jain12.6K views
Supercharging WordPress Development - Wordcamp Brighton 2019 by Adam Tomat
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
Adam Tomat612 views
Integration-Monday-Stateful-Programming-Models-Serverless-Functions by BizTalk360
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
BizTalk360244 views
Make BDD great again by Yana Gusti
Make BDD great againMake BDD great again
Make BDD great again
Yana Gusti84 views
Binary Studio Academy: Concurrency in C# 5.0 by Binary Studio
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio273 views
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript... by Tim Chaplin
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Tim Chaplin947 views
End to-end async and await by vfabro
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro1.5K views
Persistent mobile JavaScript by Yorick Phoenix
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScript
Yorick Phoenix830 views
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless by KatyShimizu
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
KatyShimizu845 views
[NDC 2019] Enterprise-Grade Serverless by KatyShimizu
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu118 views
Douglas Crockford: Serversideness by WebExpo
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo1.3K views
Buildingsocialanalyticstoolwithmongodb by MongoDB APAC
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
MongoDB APAC297 views
Performance tuning with zend framework by Alan Seiden
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend framework
Alan Seiden7.7K views
Javascript Everywhere by Pascal Rettig
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig2.2K views
Future Decoded - Node.js per sviluppatori .NET by Gianluca Carucci
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci235 views
Leveling Up With Unit Testing - php[tek] 2023 by Mark Niebergall
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
Mark Niebergall48 views
Building Efficient and Reliable Crawler System With Sidekiq Enterprise by Gary Chu
Building Efficient and Reliable Crawler System With Sidekiq EnterpriseBuilding Efficient and Reliable Crawler System With Sidekiq Enterprise
Building Efficient and Reliable Crawler System With Sidekiq Enterprise
Gary Chu985 views

Recently uploaded

Uni Systems for Power Platform.pptx by
Uni Systems for Power Platform.pptxUni Systems for Power Platform.pptx
Uni Systems for Power Platform.pptxUni Systems S.M.S.A.
58 views21 slides
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De... by
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Moses Kemibaro
29 views38 slides
DRBD Deep Dive - Philipp Reisner - LINBIT by
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBITShapeBlue
62 views21 slides
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...ShapeBlue
65 views28 slides
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueShapeBlue
96 views20 slides
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
46 views35 slides

Recently uploaded(20)

Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De... by Moses Kemibaro
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Moses Kemibaro29 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue62 views
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue65 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue96 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue46 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software344 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue145 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue119 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc77 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10369 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue88 views
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue82 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue63 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays40 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue54 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue96 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue131 views

Wrangling WP_Cron - WordCamp Grand Rapids 2014

  • 1. @cklosowski cklosows Wrangling WP_Cron Scheduling Your Tasks the WordPress Way
  • 2. Chris Klosowski • Plugin Developer (WP-Push.com, PostPromoterPro.com, GitHub, WordPress.org) • Contributing Developer and Support Tech for Easy Digital Downloads • Hang out with my Wife and Kid @cklosowski cklosows
  • 3. WP_Cron A tool to replace a tool
  • 4. What is “Cron” • A time-based job scheduler in Unix-like computer operating systems. • Used to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. • Cleanup, populate data into cache, etc.
  • 6. WP_Cron vs Cron • Works on Windows based systems • Works when you don’t have access to cron • Easily allows access to the WordPress core • “Reliably” available to Theme and Plugin developers
  • 7. Basic Usage <?php wp_schedule_event( $timestamp, $recurrence, $hook, $args ); Simple Right?
  • 9. $timestamp • The first time you want this item to run • UNIX Timestamp format • Always in UTC (not localized timezone) • Use time(); as it uses GMT for right now • No Default get_option( 'gmt_offset' );
  • 10. $recurrence • The name of the schedule value • hourly • twicedaily • daily • Using cron_schedules filter, you can add your own recurrences. • Not a timestamp, but a string that references a timestamp • Number of seconds between occurrences
  • 11. $hook • Essentially does a do_action() when it runs. You would then attach a function to this hook you’re creating. • Possible issue on some systems where the hook must not contain underscores or uppercase characters. (Have not seen this myself)
  • 12. $args • Optional array of data to pass through the hook • Great for when doing post or page specific crons • Used later when doing lookups for scheduled crons. • Must be an indexed array (no numeric keys)
  • 13. // Be Kind, Rewind register_deactivation_hook( __FILE__, 'ck_deactivation' ); function ck_deactivation() { wp_clear_scheduled_hook( 'ck_hourly_event_hook' ); } <?php register_activation_hook( __FILE__, 'ck_activation' ); ! function ck_activation() { wp_schedule_event( time(), 'hourly', 'ck_hourly_event_hook' ); } ! add_action( 'ck_hourly_event_hook', 'ck_do_this_hourly' ); function ck_do_this_hourly() { // do something every hour }
  • 14. <?php // Situation of single event $args = array( 'post_id' => 42, 'service' => 'twitter' ); wp_schedule_single_event( time(), 'ck_single_event', $args ); ! ! // Clear with same hook and EXACT same args $args2 = array( 'post_id' => 42, 'service' => 'twitter' ); wp_clear_scheduled_hook( 'ck_single_event', $args2 );
  • 15. Why Not WP_Cron? Not all unicorns and rainbows
  • 16. Because WP_Cron _______________ • Why WP Cron Sucks
 http://www.lucasrolff.com/wordpress/why-wp-cron-sucks/ • Disabling WP-Cron in WordPress
 http://www.limecanvas.com/disabling-wp-cron-in-wordpress/ • Understanding WP Cron, and why I don’t use it
 http://chrislema.com/understanding-wp-cron/
 
 
 …I could go on…
  • 17. Low Traffic Sites • WP_Cron is based off traffic • No visits, no cron • Unreliable for time specific tasks
  • 18. High Traffic Sites • Possibility of many concurrent cron events. • Expensive cron events can cause load issues. • If needing EXACT times, still not 100%
  • 19. Race Conditions • Identified by the same scheduled task running twice, at the same time. • Due to PHP threads, they aren’t aware of each other
  • 20. Missed Tasks • They will run. • Scenario • Tasks scheduled 8a and 9a. • No cron run until 9:15a • Both tasks will run at 9:15a • Be aware of this when: • Pushing to Web Services • APIs
  • 21. How to Wrangle WP_Cron • 3rd party ping service (Pingdom) • Setup an actual cron if available
 http://domain.com/wp-cron.php?doing_wp_cron=1
 
 • Limit threads with DB or file locks • Know what crons are scheduled, and what they do define('DISABLE_WP_CRON', true);
  • 22. @cklosowski cklosows Questions? Scheduling Your Tasks the WordPress Way