I currently have some working example code where when a URL path i defined using hook_menu has been passed; My custom module will use file_get_path() to pull a txt file from another ftp server. It will then return $data. The source data is stored that each line is a record. So I simply read the file one line at a time and use the explode() method to break the data into its components. From that I have it building a string in the format of a JSON at this point I return it to the user as a consumable JSON. This is used for my front end JavaScript. The problem is this data in the txt file changes very little over time. (its updated every night but very little changes).
I would like to reduce my request time by moving the fetch of the txt file to a cron job and build the JSON and save it in a sub directory of the Files directory. That way every request for the JSON data will be quick and not require a file_get_contents() and will also not require building the JSON data on every request.
I have been looking into the Files API and the hook_cron but very few quality examples show how to create a file or run a cron. I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.
I'm using Drupal 7
UPDATE:
I tried the following: (objective to make sites/mysite.com/files/myDir/test.txt)
//File Name: MyModule_cron.inc
function MyModule_cron(){
$baseDir = 'public://myDir';
$fileContent = "hello world";
file_prepare_directory($baseDir);
file_put_contents($baseDir.'/test.txt', $fileContent);
}
This is loaded in from an inc file (added into the info file) and I have cleared my cashe then run cron. I then check in the sites files
folder. The myDir
is not created along with the file not being made. Is there something i'm missing? I'm not getting any error messages when running cron.
module_load_include
in your .module file instead.