Q: Execute PHP code once per week in a Wordpress single.php template I have the below code in my single.php template. It retrieves a price from an external website, then, if it's different than the existing price custom field, it updates the meta value. 
That part works as intended. What I'd like to do, though, is only check this and update it once a week rather than with each page load. 
At first, I thought I could do it based on the post modified date, but apparently that doesn't change when updating post meta. 
If I could somehow incorporate this into functions.php to update all posts weekly, that would be even better. But, it's fine if it only triggers on the post's load too. I'm sure there's a way to schedule a cron for it, but I'm unfamiliar with programming crons.
<!-- Check external price -->
<?php 
    if(get_field('xpath_price')) { 
        libxml_use_internal_errors(true);
        $doc = new DomDocument();
        $url = get_field('_scrape_original_url');
        $doc->loadHTML(file_get_contents($url));
        $xpath = new DOMXPath($doc);
        $query = get_field('xpath_price');
        $metas = $xpath->query($query);
        foreach ($metas as $meta) {
            $priceexternal1 = preg_replace("/(.*?)(\.)(.*)/", "$1", $meta->nodeValue);
            $priceexternal = preg_replace("/[^0-9]/", "", $priceexternal1);
        }
        echo '<h3>External Price</h3>';
        echo $priceexternal;
    } 
?>

<!-- Update post_meta if different -->
<?php 
    if ($priceexternal && ($priceexternal) <> (get_field('price'))) {
        global $post;
        update_post_meta( $post->ID, 'price', $priceexternal ); 
        $priceout = $priceexternal;
    } elseif(get_field('price')) {
        $priceout = preg_replace("/[^0-9]/", "", get_field('price'));
    }
?>  


A: The whole wp-cron system can be a bit confusing for the uninitiated, although it definitely is the correct way of doing what you want. However, if you're not happy getting to grips with it, you could use a simple transient set to expire after a set period (see Codex)
For example...
if ( !get_transient( 'my-price-timer' ) ) { 
    // no transient exists, so process price check
    if(get_field('xpath_price')) {
        // etc
    }
    // now create the transient to say that we've done it
    set_transient( 'my-price-timer', 'done', WEEK_IN_SECONDS );
}


A: https://codex.wordpress.org/Function_Reference/wp_cron
 add_filter( 'cron_schedules', 'cron_add_weekly' );

 function cron_add_weekly( $schedules ) {
    // Adds once weekly to the existing schedules.
    $schedules['weekly'] = array(
        'interval' => 604800,
        'display' => __( 'Once Weekly' )
    );
    return $schedules;
 }

then 
if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
  wp_schedule_event( time(), 'weekly', 'my_task_hook' );
}

add_action( 'my_task_hook', 'get_prices_function' );

function get_price_function() {
  // Your function
}

