How to Schedule a Cron Job in WordPress Without Using a Plugin?

I’m trying to set up a cron job in my WordPress website, I don’t want to use any plugin for this purpose. Could someone guide me on how to manually schedule a cron job in WordPress?

Follow these steps to create your own custom cron job.

  1. Open functions.php file of your theme.
  2. Add custom cron interval (optional). You can use wordpress default cron interval.
// Set the interval in seconds (e.g., 3600 seconds = 1 hour)
function cron_1hr_intervals($schedules) {
    $schedules['1hr_cron'] = array(
        'interval' => 3600, 
        'display' => __('1hr Interval'),
    );
    return $schedules;
}
add_filter('cron_schedules', 'cron_1hr_intervals');
  1. Register the Cron Event
function register_cron_event() {
    // Schedules the event if it's NOT already scheduled.
    if ( ! wp_next_scheduled ( 'run_vidsrc' ) ) {
        wp_schedule_event( time(), '1hr_cron', 'custom_cron_event' );
    }
}
add_action( 'init', 'register_cron_event');
  1. Create the functionality for the cron
function run_custom_cron() {
    // Do something here.
}
add_action( 'custom_cron_event', 'run_custom_cron');

Note: you can use the following code to clear any unused cron event.

wp_clear_scheduled_hook( 'custom_cron_event' );

Also check all existing cron event with following code.

$cron_jobs = get_option( 'cron' );
var_dump($cron_jobs);