Solved

php: time increment

Posted on 2004-04-30
15
565 Views
Last Modified: 2006-11-17
ok, I have a php file name hourly.php. It calculates results for me. In order to execute it, I input three values, the start time, end time and time window such as start time:   20040430040000
                                                    end time:   2004043004000
                                              time_window:  hourly
by using cmd (command prompt) i execute this line:
php hourly.php 20040430040000 2004043004000 hourly

then this calculates the results to my stats database.
what i need help is to be able to write a php code to have my schedule task to run php file to execute this every hour but the date and time changes so I don't know what is the best way to do it or even how. With that, i don't need to input manually to the cmd to input these three parameter every hour. I like to be able to schedule task that particular php file to run that every hour for me incrementing hourly.I hope this is enough.
any help is greatly apprecieated.
mahalo,
-t
0
Comment
Question by:imaw
  • 8
  • 7
15 Comments
 
LVL 14

Expert Comment

by:cracky
Comment Utility
Are you running on *nix or Windows?
0
 
LVL 14

Expert Comment

by:cracky
Comment Utility
Judging by your terminology, you are running Windows, so Windows Task scheduler is you best option.

You would first need to create a batch file of the required commands for your script. In case you didn't know, a batch file is simply a set of command line instructions saved to a text file with a .bat extension.

The only point of confusion for me is how you determine the first 2 time parameters. Are they based on the current time? If so, I would just use the strftime("%Y%m%d%H%M%S",time()) function in your PHP script to get the value in the way you would like.

Then tell windows scheduler to run this file on an hourly basis. A good tutorial on how to use Windows Scheduler is here:

http://www.iopus.com/guides/winscheduler.htm

If this isn't enough information, please let me know exactly what you are trying to do with the parameters and I can help you format them.
0
 

Author Comment

by:imaw
Comment Utility
Thanks for your reply. Originally I wanted to use a batch file to run my script but I realize that I have dates and time changing. I need help to create a php file that will increment my date and time correctly every hour since the every month has up to 30 or 31 days in the month. Right now to run my php file, I go to cmd to call my php file in this way:

php hourly.php 20040430040000 2004043004000 hourly

That give me a start time, end time and the type of time window. Hopefully I can create a php function that is smart enought to increment every hour on it's owns so I don't have manually input the three values. I hope this help and thanks for helping.
-t
as far as windows scheduling, that will be no problem. I have a few window scheduler running a few batch files for the same application I been trying to built.
0
 
LVL 14

Expert Comment

by:cracky
Comment Utility
You need to be more specific as to how your start and end times are determined. Do you just decide what numbers to enter, or are they based on the current time?

If they are based on the current time, then your PHP script can easily run according to whatever the value of time() is. If you need your variables in YYYYMMDDHHMMSS format, you can achieve this in your PHP script with strftime("%Y%m%d%H%M%S",time())
0
 

Author Comment

by:imaw
Comment Utility
Good question. I would like to my start time to be 24 hours a day. for example, 7-8, 8-9,9-10,10-11,11-12,13-14,14-15,15-16 etc... throughout the day.I'm running a stats php file. In fact i'll post the code that i have so you can see exactly what it does. Line 23-25 is what i'm trying to input. Thanks again.
***************************************************************
<?
   #error_reporting($_ALL ^ E_NOTICE);

   require_once('./includes/MySQL.Recordset.php');

   $DB_HOST = 'DEVIT';
   $DB_NAME = 'flexlm2';
   $DB_USER = 'xxxx';
   $DB_PWD  = 'xxxx';

   $APP  = '';
   $USER = '';
   $FREE = '';

   $UNIQUE_USERS = '';
   $SESSIONS = '';
   $MAX_USERS = '';
   $MIN_USERS = '';
   $AVG_USERS = '';
   $MAX_OUT_LICS = '';
   $NUM_POLLS = '';

   $start = ($_REQUEST['start'] != '') ? $_REQUEST['start'] : $argv[1];
   $end   = ($_REQUEST['end'] != '') ? $_REQUEST['end'] : $argv[2];
   $timewindow  = ($_REQUEST['timewindow'] != '') ? $_REQUEST['timewindow'] : $argv[3];

   print("Start:" . $start . "\r\n");
   print("End:" . $end . "\r\n");
   print("Window:" . $timewindow . "\r\n");

   $sql = "select timestamp, application, module, users, computername, sequence, comments, batchtime
           from flexlm2.flextable
           where batchtime >= '$start'
             and batchtime <  '$end'
           order by batchtime asc, application, module, users";

   $conn = mysql_connect($DB_HOST,$DB_USER,$DB_PWD);
   mysql_select_db($conn,$DB_NAME);

   # Open cursor to database
   $rs = new MySQLRecordset($conn,$sql);

   # Cycle through each record in sequential order (by date/time)
   for ($i=1;$i<=$rs->rowCount;$i++)
   {
       $timestamp    = $rs->fields[$i]['timestamp'];
       $application  = $rs->fields[$i]['application'];
       $module       = $rs->fields[$i]['module'];
       $users        = $rs->fields[$i]['users'];
       $computername = $rs->fields[$i]['computername'];
       $sequence     = $rs->fields[$i]['sequence'];
       $comments     = $rs->fields[$i]['comments'];
       $batchtime    = $rs->fields[$i]['batchtime'];

       $APP[$application][$module][$batchtime][$user][$timestamp]++;
       $USER[$application][$module][$user][$timestamp]++;

       print($application . "\t" . $module . "\t" . $users . "\t" . $timestamp . "\r\n");
   }


   $sql  = "select application, module, batchtime, total_free
            from flexlm2.license
            where batchtime >= '$start'
              and batchtime <  '$end'
            order by application, module, batchtime";

   print($sql);

   $rs = new MySQLRecordset($conn,$sql);
   for ($i=1;$i<=$rs->rowCount;$i++)
   {
       $application  = $rs->fields[$i]['application'];
       $module       = $rs->fields[$i]['module'];
       $batchtime    = $rs->fields[$i]['batchtime'];
       $license_free  = $rs->fields[$i]['total_free'];

       #print($application . "\t" . $module . "\t" . $batchtime . "\t" . $license_free . "\r\n");

       $FREE[$application][$module][$batchtime] = $license_free;
       print('drw $FREE[' . $application . '][' . $module . '][' . $batchtime . '] = ' . $FREE[$application][$module][$batchtime] . "\r\n");
   }

   ###############################
   # Create statistics
   ###############################

   # Determine unique users
   # Determine number of sessions
   foreach ($USER as $application => $M1) {
      foreach ($M1 as $module => $M2) {
         $UNIQUE_USERS[$application][$module] = 0;
         $SESSIONS[$application][$module] = 0;
         foreach ($M2 as $user => $M3) {
            $UNIQUE_USERS[$application][$module]++;
            foreach ($M3 as $timestamp => $value) {
               $SESSIONS[$application][$module]++;
            }
         }
      }
   }

   # Determine Minimum users for Time Window
   # Determine Maximum users for Time Window
   # Determine Average users for Time Window
   foreach ($APP as $application => $M1) {
      foreach($M1 as $module => $M2) {
         foreach($M2 as $batchtime => $M3) {
              print('AAA $FREE[' . $application . '][' . $module . '][' . $batchtime . '] = ' . $FREE[$application][$module][$batchtime] . "\r\n");

            foreach($M3 as $user => $M4) {
               $USERCT[$application][$module][$batchtime]++;
               foreach($M4 as $timestamp => $value) {
               }
            }
         }

         $MIN_USERS[$application][$module] = 1000000;
         $MAX_USERS[$application][$module] = 0;
         $AVG_USERS[$application][$module] = 0;
         $NUM_POLLS[$application][$module] = count($USERCT[$application][$module]);
         $MAX_OUT_LICS[$application][$module] = 0;

         foreach ($USERCT[$application][$module] as $batchtime => $value)
         {          
              if ($value < $MIN_USERS[$application][$module])    { $MIN_USERS[$application][$module] = $value; }
              if ($value > $MAX_USERS[$application][$module])    { $MAX_USERS[$application][$module] = $value; }
              print('1 $FREE[' . $application . '][' . $module . '][' . $batchtime . '] = ' . $FREE[$application][$module][$batchtime] . "\r\n");
              if ($FREE[$application][$module][$batchtime] <= 0) { $MAX_OUT_LICS[$application][$module]++; }
              $AVG_USERS[$application][$module] += $value;
              print('2 $FREE[' . $application . '][' . $module . '][' . $batchtime . '] = ' . $FREE[$application][$module][$batchtime] . "\r\n");


              print('3 $FREE_LICS[' . $application . '][' . $module . '][' . $batchtime . '] = ' . $FREE[$application][$module][$batchtime] . "\r\n");
              $FREE_LICS[$application][$module] += $FREE[$application][$module][$batchtime];


         }
         $AVG_USERS[$application][$module] = $AVG_USERS[$application][$module]/(count($USERCT[$application][$module]));
                         $FREE_LICS[$application][$module] = $FREE_LICS[$application][$module]/(count($USERCT[$application][$module]));
                         print("cody:" . $FREE_LICS . "hi\r\n");
      }
   }


   # Display all the information
   foreach ($APP as $application => $M1) {
      foreach($M1 as $module => $value ) {
         $sql  = "insert into flexlm2.stats(application,module,time_window,start_time,end_time,";
         $sql .= "license_free,unique_users,num_log_in,max_users,min_users,avg_users,";
         $sql .= "maxout_poll_time,num_poll_times) values (";
         $sql .= "'" . $application . "',";
         $sql .= "'" . $module . "',";
         $sql .= "'" . $timewindow . "',";
         $sql .= "'" . $start . "',";
         $sql .= "'" . $end . "',";
         $sql .= $FREE_LICS[$application][$module] . ",";
         $sql .= $UNIQUE_USERS[$application][$module] . ",";
         $sql .= $SESSIONS[$application][$module] . ",";
         $sql .= $MAX_USERS[$application][$module] . ",";
         $sql .= $MIN_USERS[$application][$module] . ",";
         $sql .= $AVG_USERS[$application][$module] . ",";
         $sql .= $MAX_OUT_LICS[$application][$module] . ",";
         $sql .= $NUM_POLLS[$application][$module] . ")";

         print($sql . "\n");

         mysql_query($sql,$conn);
      }
   }
?>
*************************************************************************************
0
 

Author Comment

by:imaw
Comment Utility
cracky,
How about this. If i was to run my batch file to call my php file for example like if I run the batch file at 12:05 pm, it will subtract the current time which is i think is 3600 seconds which will give me 11:00am and then add 3600 seconds for the end time and that will give me 12:00 pm. How can I do this?
0
 

Author Comment

by:imaw
Comment Utility
cracky,
This is what I came up with.
<?
$now = time();
$start_time = $now - 3600;
$end_time = $start_time + 3600;
?>


But I am wondering if there is a way that I can round it off minus the hour before so that If i ran my batch file to call this php file at 12:05 and round it to 11:00?
-t
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 14

Accepted Solution

by:
cracky earned 500 total points
Comment Utility
Sorry for the delayed reply, time zone difference :)

I am assuming your `batchtime` column in your database is of DATETIME format. Note that the MySQL DATETIME format is YYYY-MM-DD HH:MM:SS and not YYYYMMDDHHMMSS, although it understands that format if it is well formed.

What you are asking can be done quite easily with a strftime function combined with strtotime("-1 hour") based on the curren time.

Assuming you are running the query every hour at HH:05 and want to process the previous hour, this is how you would calculate the times:

Note that you will no longer need your args, since the script will automatically calculate the times based on the current time. You timewindow is fixed to hourly, but is you really want to add the timewindow argument, it is fairly easy to do.

<?php
$start = strftime("%Y%M%D%H0000" , strtotime("- 1 hour"));
$end = strftime("%Y%M%D%H5959" , strtotime("- 1 hour"));
?>

Your MySQL query would then look like this:

<?php
$sql = "select timestamp, application, module, users, computername, sequence, comments, batchtime
           from flexlm2.flextable
           where batchtime between '$start' and '$end'
           order by batchtime asc, application, module, users";
?>

If you would like me to explain any of the functions used, please let me know.
0
 
LVL 14

Expert Comment

by:cracky
Comment Utility
Note that your way will also work, but that you cannot always rely on the scheduler to run at exactly the same second that you request. The script can also take an arbitrary time to execute, so you may miss some entries in the database if you subtract a value in seconds from the current time.

That is why I used the format strftime("%Y%M%D%H0000" , strtotime("- 1 hour"));

This means that the script could run at any time between say 12:00 and 12:59:59 and you will still get the right result from the previous hour, since your start and end times have a fixed MM:SS time.
0
 

Author Comment

by:imaw
Comment Utility
cracky, you are da man. It didn't work at first. The numbers weren't what I was looking for but i made some changes. Here' what i have.Thanks to you i am able to round off correctly. I had to use the small m and d and delete the space between - and 1 and it works like a champ.
**********************
<?php
$start = strftime("%Y%m%d%H0000" , strtotime("-1 hour"));
$end = strftime("%Y%m%d%H5959" , strtotime("-1 hour"));
print $start;
print "<br>";
print $end;
?>
*****************************
I was hoping you can still help me since i'm a newbie at this. I need to somehow be able to send those three values to hourly.php and I know I have to erase line 23-25 of hourly.php which is shown above for who knows what. My guess is that I should make hourly.php a huge function and create a shell for time_increment.php(the code you help me with). time_increment should have some php shell saying something like for my cmd(win2000) php hourly.php $start $end hourly. Is that correct or how would you do it. You definately deserve more points than 500.
-t
0
 
LVL 14

Expert Comment

by:cracky
Comment Utility
Oops, yes that was my mistake, I meant to use %m%d. I was in a hurry :)

If you only intend to run this script hourly and only intend to process the previous hour each time, then you don't even need to pass *any* parameters to the script, since the script is simply using the current time that the script is running to determine the time window. Every time the script runs, the time() value will be different, since the schedule calls it at hourly increments.

Assuming you have PHP version >= 4.3, you will be using the CLI binary to execute your script from the command line. In order to understand more about how PHP runs from the command line, you might need to read:
http://au2.php.net/features.commandline
It's a long read, but worth it if you will be writing these types of scripts often.

This is the sort of information you would have in your batch file called hourly_php.bat:

@c:\php\cli\php.exe hourly.php

I am only familiar with running cron jobs from the command line on BSD Unix / Linux, so you might need to tweak your batch file a little for Windows, but I think I have it pretty spot on. I assume your hourly.php file needs to be in the same directory as your batch file to run without specifying the path.

So, you would have these files in the same directory:

hourly.php
<?php
// Your PHP code to run every hour as previously discussed
?>

hourly_php.bat
@c:\php\cli\php.exe hourly.php

You would then use Windows Task Scheduler to run hourly_php.bat every hour at HH:05 to process for the previous hour. You would then never need to call this script from the command line again and you wouldn't need to change any parameters.

I hope this all makes sense :)
0
 

Author Comment

by:imaw
Comment Utility
Sorry for the delay. Wow that was a long read. I didn't know there's so many ways to do it. I'm going to give it a shot today and hopefully it works. I'll let you asap.
0
 

Author Comment

by:imaw
Comment Utility
I didn't do too well. so sorry, it's still a little complicated. I may need more visual help or exact example but that is too much to ask from ya(is that a possiblity?). I am so close though. I guess i'll keep trying.
-t
0
 

Author Comment

by:imaw
Comment Utility
cracky,
believe it or not. I got it to work.
I created hourly.php one big function and called that function from the time_increment.php file. It seems to be working. Now I just have schedule task pointing to the time_increment.php file and that drives everything. Your rounding off the hour before works great.
Thanks for your patience and help and understanding.
Much mahalo.
-t
0
 
LVL 14

Expert Comment

by:cracky
Comment Utility
Glad you got it worked out. Sorry for the late last reply. I have a lot of work to start the week, so didn't get to it in time :(
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
get the data all row not only one row php 4 35
Modify PHP Code on the Fly? 8 38
Link SQL table to Webpage 9 34
PHP string issue 5 16
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now