概要
wp_schedule_event
関数は、繰り返し実行するアクションをスケジュールに登録するための関数です。主に以下のような機能を実装する際によく使用されます。
- 定期的なデータベースのバックアップ
- 一定間隔でのキャッシュクリア
- バルクメールキャンペーンの送信
- 定期的なデータのインポート・エクスポート処理
- ユーザー通知の送信
- RSSフィードの更新
- カスタム投稿タイプの自動生成
- プラグインの定期的なメンテナンス作業
構文
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
パラメータ
$timestamp
(int): イベントの最初の実行日時のUNIXタイムスタンプ。$recurrence
(string): 繰り返しの頻度を示す文字列(例: ‘hourly’, ‘twice_daily’, ‘daily’)。$hook
(string): スケジュールされたイベントが発生したときに実行されるアクションフックの名前。$args
(array): フックに渡す追加の引数(オプション)。
戻り値
- 成功した場合は
true
、失敗した場合はfalse
を返す。
関連する関数
使用可能なバージョン
- 3.0.0 以降
コアファイルのパス
wp-includes/cron.php
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
- 簡単な時刻ごとのイベントスケジュール
if ( ! wp_next_scheduled( 'my_hourly_event' ) ) {
wp_schedule_event( time(), 'hourly', 'my_hourly_event' );
}
このコードは、my_hourly_event
というフックを1時間ごとに実行するイベントをスケジュールします。
- カスタム関数をスケジュールに登録
function my_custom_function() {
// 定期実行する処理
}
add_action( 'my_custom_event', 'my_custom_function' );
if ( ! wp_next_scheduled( 'my_custom_event' ) ) {
wp_schedule_event( time(), 'daily', 'my_custom_event' );
}
このコードは、my_custom_function
を毎日実行するためのイベントをスケジュールします。
- スケジュールされたイベントのクリア
function clear_my_scheduled_event() {
$timestamp = wp_next_scheduled( 'my_hourly_event' );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, 'my_hourly_event' );
}
}
add_action( 'wp_loaded', 'clear_my_scheduled_event' );
このコードは、my_hourly_event
のスケジュールされたイベントを解除します。
- カスタム頻度の追加
add_filter( 'cron_schedules', 'custom_cron_schedules' );
function custom_cron_schedules( $schedules ) {
$schedules['every_five_minutes'] = array(
'interval' => 300,
'display' => __( 'Every Five Minutes' ),
);
return $schedules;
}
if ( ! wp_next_scheduled( 'my_five_minute_event' ) ) {
wp_schedule_event( time(), 'every_five_minutes', 'my_five_minute_event' );
}
このコードは、5分ごとのカスタムスケジュールを追加し、それを使ってイベントをスケジュールします。
- 引数付きのイベントスケジュール
function my_event_function( $arg ) {
// 引数に基づく処理
}
add_action( 'my_event_with_args', 'my_event_function' );
if ( ! wp_next_scheduled( 'my_event_with_args' ) ) {
wp_schedule_event( time(), 'daily', 'my_event_with_args', array( 'my_argument' ) );
}
このコードは、引数 my_argument
を持つ my_event_function
を毎日実行するイベントをスケジュールします。