-4

Is there any method or function in php to delay a function execution after a period of time

<?php 

function create_file()
{
$myfile = fopen("newfile1.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "hello\n";
fwrite($myfile, $txt);
fclose($myfile);
}

function delete_file()
{
 unlink("newfile1.txt"); //delete after 24 H
}

?>

I create many files and some time the execution of the code breaks and the file it can be deleted after using the file.

So I want to execute the delete function after 24 h of the file creation. it ts possible to do that with php

any help will be appreciated

Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
  • 3
    Look into cron jobs/scheduled tasks – John Conde Jan 15 '15 at 14:02
  • I believe you cant do this the way you want in php. It operates line by line when called once its finished it wont re run until the page is reloaded. To use php You should look into getting current time and cookies to see if the page is reloaded after the 24 hour period, if it is run that code. BUT this will have to be done when the user reloads the page – NoLiver92 Jan 15 '15 at 14:05
  • It's not a web site. it's a simple php script to create and delete file – Anis_Stack Jan 15 '15 at 14:09

2 Answers2

1

Install a cronjob that runs every 24h. In that file check for the creation date of the file. If it is 24h or more, delete it. You can use this topic for file deletion.

Community
  • 1
  • 1
  • Does not answer the OP question – NoLiver92 Jan 15 '15 at 14:07
  • 2
    Why not? He want to delete posts older than 24 hours, cronjob is the way to do it properly? –  Jan 15 '15 at 14:07
  • 1
    I understand that, But that's not what NoLiver92 said. I think that this does answer the OP question. I agree it would've been better if I posted more content instead of just a link. –  Jan 16 '15 at 13:07
0

It's a CLI program, so you have 2 ways of doing this:

-Use a cronjob that runs a php script that does the checkings for deletion.

-Use php sleep function and wait 24 hour (thread will be blocked).

Blaatpraat
  • 2,829
  • 11
  • 23