The best way to do this is, write the above code in your themes function.php. In this way you will have access to all the WP inbuilt functions, hooks, actions etc.
Then use Cronjob Scheduler plugin – https://wordpress.org/plugins/cronjob-scheduler/ to run your function periodically.