Viewed   290 times

I need some information regarding starting and stopping a timer in PHP. I need to measure the elapsed time from the start of my .exe program (I'm using exec() function in my php script) until it completes the execution and display the time it took in seconds.

How can I do this?

 Answers

2

You can use microtime and calculate the difference:

$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;

Here's the PHP docs for microtime: http://php.net/manual/en/function.microtime.php

Monday, October 17, 2022
1

Judging from "when ever a user opens the page" there should not be an auto-update mechanism of the page? If this is not what you meant, look into AJAX (as mentioned in the comments) or more simply the HTML META refresh. Alternatively, use PHP and the header()

http://de2.php.net/manual/en/function.header.php

method, described also here:

Refresh a page using PHP

For the counter itself, you would need to save the end date (e.g. a database or a file) and then compare the current timestamp with the saved value.

Lets assume there is a file in the folder of your script containing a unix timestamp, you could do the following:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

You can use http://www.unixtimestamp.com/index.php to get familiar with the Unix Timestamp.

There are many ways that lead to rome, this is just one of the simple ones.

Tuesday, October 4, 2022
4

Or would it be better to let the service run regardless of the phone's status and bind/unbind to/from it when needed.

Please don't. It will just take up RAM for no good reason. It is everlasting services like this that cause users to attack developers with task killers.

Are there any best practices out there regarding the implementation of services?

Here are two of my posts on the subject, for what they're worth.

Sunday, September 11, 2022
 
ashiina
 
1

This looks like a problem:

private boolean startTimer() {
    // ......
        if (_TimerFuture != null) {
            _TimerFuture.cancel(false);
        }

        _TimerFuture = _Timer.schedule(new TimerPopTask(), 
                                       TIMER_IN_SECONDS, 
                                       TimeUnit.SECONDS);
    // ......
}

Since you're passing a false to cancel, the old _TimerFuture may not get cancelled if the task is already running. A new one gets created anyway (but it won't run concurrently because your ExecutorService has a fixed thread pool size of 1). In any case, that doesn't sound like your desired behavior of restarting a timer when startTimer() is called.

I would rearchitect a bit. I would make the TimerPopTask instance be the thing you "cancel", and I would leave the ScheduledFutures alone once they are created:

private class TimerPopTask implements Runnable  {
    //volatile for thread-safety
    private volatile boolean isActive = true;  
    public void run ()   {  
        if (isActive){
            TimerPopped();
        }
    }  
    public void deactivate(){
        isActive = false;
    }
}

then I would retain the instance of TimerPopTask rather than the instance of ScheduledFuture and rearrange startTimer method thusly:

private TimerPopTask timerPopTask;

private boolean startTimer() {
    try {
        if (timerPopTask != null) {
            timerPopTask.deactivate();
        }

        timerPopTask = new TimerPopTask();
        _Timer.schedule(timerPopTask, 
                        TIMER_IN_SECONDS, 
                        TimeUnit.SECONDS);
        return true;
    } catch (Exception e) {
        return false;
    }
}

(Similar modification to stopTimer() method.)

You may want to crank up the number of threads if you truly anticipate needing to 'restart' the timer before the current timer expires:

private ScheduledExecutorService _Timer = Executors.newScheduledThreadPool(5);

You may want to go with a hybrid approach, keeping references to both the current TimerPopTask as I described and also to the current ScheduledFuture and make the best effort to cancel it and free up the thread if possible, understanding that it's not guaranteed to cancel.

(Note: this all assumes startTimer() and stopTimer() method calls are confined to a single main thread, and only the TimerPopTask instances are shared between threads. Otherwise you'll need additional safeguards.)

Thursday, December 22, 2022
 
3

You can interrupt the execution of your script using sleep(). If you want sub-second precision, you can use usleep():

# wait half a second (500ms)
usleep(500000);
echo 'Success';
Monday, October 3, 2022
 
mogli
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :