Countdown timer that counts down the execution of php script - javascript

I am trying to add on a script of mine that is checking some factors for multiple websites a COUNTDOWN that will let the user know, live, how many hours/minutes/seconds will remain until script finishes the task. I need to do this to a php script of mine. But really don't know where to get started. I only know that is possible to COUNT the time of a script HAD BEEN executed with microtime() function. I tried searching lots of scripts here, but I barely found smth related to some dynamic progress bars (but not very well explained) and nothing to a dinamic countdown timer that can countdown execution time of script.
Would be much appreciated any help related this issue (links, functions, scripts...)

Without knowing what your script does, there is no way to know ahead of time how long it will take to run. Even if we did know what it does, to know the precise time it will take to run really is not possible. If this is all within the same session you could put "% complete markers" at certain main points in your script. I do this in a few places. It makes a nice progress bar and I also show the total elapsed run time as well. If something like this is what you want then read on...
(this is using a jQuery UI progress bar)
If your script is a loop and each iteration is basically doing the same thing then the growth of the progress bar will be pretty fluid. If this isn't the case, and your script does many things very fast, then a few things very slow, then you bar will be like pretty much all Windows progress bars :) It could get to a certain point very quickly then hang there for a while.
Not at my PC so I'm sure there are typos below but you should be able to get the point. Hope this helps...
Something like this would be in your long running script...
$_SESSION["time_start"] = microtime(true);
$_SESSION["percentComplete"] = 0;
... some of your php script ...
$_SESSION["percentComplete"] = 10;
... some of your php script ...
$_SESSION["percentComplete"] = 20;
... some of your php script ...
$_SESSION["percentComplete"] = 30;
... etc ...
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script
but if your long running script is a loop it would be more like this...
$loopCnt = 0;
//your php loop
{
$loopCnt = $loopCnt+1;
//...the meat of your script...
$_SESSION["percentComplete"] = round(($loopCnt/$totalRecordCount)*100);
}
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script
Then on the page the user interacts with an ajax ping could be setup to check the value of $_SESSION["percentComplete"] every couple seconds or so and make the progress bar grow based off the result. Something like...
function checkScriptProgress()
{
$.ajax({
url: "checkScriptProgress.php",
type: 'get',
cache: false,
success: function( data, textStatus, jqXHR) {
//(1) MOVE THE PROGRESS BAR
//if you are using a jQuery UI progress bar then you could do something like...
//jQuery("#yourProgressBar").progressbar( "option", "value", data.progress );
//if you are using HTML5 progress bars it would look like...
//var pBar = document.getElementById("yourProgressBar");
//pBar.value = data.progress;
//(2) UPDATE ELAPSED TIME
//if you want to display the total run time back to the user then use: data.totalRunTime
//(3) If report is not finished then ping to check status again
if (data.progress < 100) setTimeout("checkScriptProgress();", 1000); //check progress every 1 second so the progress bar movement is fluid
})
});
}
Then the checkScriptProgress.php file would look something like...
<?php
header('Content-Type: application/json');
$time_end = microtime(true);
$time = $time_end - $_SESSION["time_start"];
echo '{"progress":'.$_SESSION["percentComplete"].',"totalRunTime":'.$time.'}';
die();
?>

Before any progress has been made, an initial estimate requires an estimate of how long each action will take to complete, and the number of actions to perform. (This formula assumes that processing is not done in parallel)
final_timestamp = start_timestamp + (number_of_actions * average_duration_per_action)
Record progress, including number of actions completed and total time spent so far. This allows you to update the estimate.
updated_final_timestamp = start_timestamp + (current_timestamp - start_timestamp) / (num_action_completed / num_actions_total)

You will never be able to determine the duration of any execution task before starting the task. Thats when artificial intelligence comes to be a part of your algorithm. You will need to train your algorithm with a large set of data that will make it possible to Predict the duration of the task.
For example you can create an INSERT statement of a major part of your application and then start counting the time using microtime(). When the insert statement is done with any other pre processing, you will save this data as a training data.
In your application now .. When someones tries to use the same Process. You will say it will take about 33 seconds for example. and you use your javascript code to control the dynamic progress bar to be in 100% state after 33 seconds!
Code Example:
<?php
//** this is done in development phase **//
function MyFunction($arg1, $arg2){
// calculate the current time.
$startTime =microtime(true);
// My Process in here ......
$final_time = microtime(true) - $startTime;
// Save final time for future usage.
// Repeate the step 100 times with random data
}
// Now you can pre calculate the average of this task
// based on the previous training data.
function MyFunction($arg1, $arg2){
// Get avarege executing time for this..
// Tell the user that this function will take ? amount of time.
}
?>
This method is more reliable and efficient than counting the time while doing the task.
You will never need to calculate the time in the middle of the task because you already did that.
You will never need an ajax that will hit your server every second
Your Progress bar is moving smoothly because you know the time it takes.
However, if you just need a dynamic progress bar that changes with every line of code you will need to manage your javascript inside your PHP code.
Finally, the last method will cause a problem if one line is taking more amount of time than other lines. Your progress bar may reach %90 in 3 seconds. and stop for 10 seconds in that state until it moves to 100%, which seems unreal.
You will need to calculate the time before you start
You will need to calculate the time after you finish
You will need to calculate the difference between the two timestamps.
And you will increase you progress bar Un dynamically.

Related

Discord javascript l Deleting data from database after the time has expired

I made a premium membership system to my discord bot, but the time starts to be minus a certain time, so I want to delete the data from the database when the time I set with ms expires. I tried something like that but it didn't work
I save the data as follows;
Looks like you are setting the interval to an incredibly long time. It looks like you are storing the specific time you want the function to run. You'll probably want to do something like this:
let interval = sure - new Date();
if(interval < 0) { // this expiration date already passed
interval = 0;
}
setInterval(function() {
db.delete(` ... `);
db.delete(` ... `);
}, interval);
However! If you do all this multiple times (like inside the 'message' handler like you're doing right now), you're gonna have a memory leak. Make sure you are setting the intervals only once.
Also, if your program crashes, you'll have to set up all the intervals again at startup.
If I was making something like this, I would instead make a cron job to check only once per day to delete all the expired members, instead of using setIntervals.

how can I make a countdown timer perform an action when it runs out?

this is my very first question here and may not meet some standards, for that i apologize in advance.
I have a site developed in laravel 5 where the users register and are expected to make take an action within a specific period after registration. I have included a countdown timer for that purpose (the time code is shown below). Now I need to automatically remove a user record from the database when the time runs out. Please how can I do that?
the timer code is:
<div class="getting-started"></div>
<?php
$time = strtotime($user['updated_at'].'+24 hours');
$countdown = strftime('%Y/%m/%d %H:%M:%S',$time);
?>
<script type="text/javascript">
$(".getting-started")
.countdown("{{$countdown}}", function(event) {
$(this).text(
event.strftime('%H:%M:%S')
);
});
</script>
If you want something to happen on the server, then you should maintain the timer on the server side, not the client side. Otherwise, the user can simply change the timer or otherwise block the action that the expiration is meant to trigger. I would store a timestamp with the user record, noting when it was created. Then write a script to loop over all records that are older than your threshold and perform the desired action on them. Then run this script via a cron that fires at a regular interval.

variable value on page change

I am new in javascript and php. I am creatng an admin panel in which I have an option for the user to play game. But the issue is, every game have a specific time period say 30 mins. So, what I want is that if a user have started the game, the count down must be started and if user once switch from that page to another page, still the counter must be counting and after 30 mins it should end the game.
For example I am on http://www.examplec.com/Game1 my count down of 30 min will start. If I switch from that page to another like http://www.example.com/order then the counter should still count the total time and when its expired, end it and send query to database.
Kindly reply if anyone know the solution. I have already find a solution using session but I want more efficient solution. One more thing a single user can play more than 1 game.
when your game start set a session of current time like this
$_SESSION['game_start_time'] = strtotime(date('d-M-Y g:i:s A')); // it will give you complete current timestamp.
and now check it on every page by including
if(isset($_SESSION['game_start_time']))
{
$game_start_time = $_SESSION['game_start_time'];
$current_time = strtotime(date('d-M-Y g:i:s A'));
$time_diff = $current_time - $game_start_time;
if($time_diff>(30*60))
{
//expire 30 minutes your code is here
}
else
{
// action if require to do when below 30 minutes of game start.
}
}
What you could do is create a table to keep track of the time, this is not the most efficient way but it would be secure.
So create a new table called gametrack with the following fiels:
id
userid
gameid
timestarted
etc
so when a user starts a game you insert a record with user info.
Next you need to edit the game page. In the game page you could place a jquery code to request for update on the time.
function gameStatus(){
$.ajax({
url: 'status.php?gid=[GAMEID]',
success: function(data) {
if(data == 1) {
//DO SOMETHING, REFRESH THE PAGE, STOP THE GAME ETC
}
}
});
}
setInterval("gameStatus()",10000);
the code above would request status.php every 10 seconds, you need to pass the gameid to the file and assuming that the user is registered you can use session to get user info and return 1 if 30 mins has passed.
You can mix this solution with Satish's Answer to use Sessions instead of Databases and still get a live count down with the jquery code above.
You can try this with localStorage
When you want to set variable:
var name = "value";
localStorage.setItem("someVarName", name);
And in any page (like when the page has loaded), get it like:
var Name = localStorage.getItem("someVarName");
Browser compatibility caniuse.com/namevalue-storage
Demo

Continually check for an Oracle record at page load

I basically have a page that when loads, reads an Oracle SQL table for a specific record id that may not currently exist at the point as it may take up to a minute to insert this specific record into the table.
Based on this, I need a means of showing a "Loading Image" while it waits for the record to exist, so has to wait. Once it does, I want to remove the loading image and present the user with the record details. I am using Oracle Application Express 4.2 for this.
My question is not so much the loading/hiding of the image but how to continually check for the record within the Oracle table, during page load.
Either I receive the record successfully and then hide the image or say after 1 minute, I dismiss the checking of the record and present the user with a message indicating that no record was found.
Sorry for my english. I will try help you.
Make your "Loading image" always visible on the page. There is no need to show it on load, you only need to hide it at proper moment.
Add Application Process to your application. Name it for example "GET_MY_ROW". Process must check your event, and return some flag, for example 1 or 0.
Example:
declare
l_cnt number;
begin
select count(*)
into l_cnt
from table1 t
where id = 12345;
if l_cnt > 0 then
htp.p(1);
else
htp.p(0);
end if;
end;
3.3 Add javascript code as page load event (for example by Dynamic Actions):
Javascript code:
var myInterval = setInteral(function {
var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=GET_MY_ROW',$v('pFlowStepId'));
get.GetAsync(function(pRequest) {
if (pRequest.readyState == 4) {
if (pRequest.responseText == 1) {
alert('Record loaded successfully');
// add function call, hiding your "Loading image" here
clearInterval(myInterval);
}
};
});
get = null;
}, 5000); //check every 5 seconds
setTimeout(function() {
alert('Sorry, no record was found. Try again later.');
clearInterval(myInterval);
}, 60000); // fail after 1 minute
Since NoGotnu already answered, I'll put this here:
Is there any reason for the procedure to be called through a job? Is it the only way to create the required record? Is the job called anywhere else? Why not call the procedure directly when the required page has been submitted and show the loading icon there? When it finishes, the user knows it has finished. That would involve a lot less fiddling around as you can make apex show a processing graphic on page submit. You could then just inform the user on the other page that the process has not been ran yet and they'd have to do that first.
Secondly, while NoGotnu's answer will work, I'd like to point out that in apex 4.2 you should use the apex.server namespace instead of the never documented htmldb_Get construction. apex.server.process is a clean implementation of the jQuery ajax setup.
NoGotnu's code translated:
apex.server.process( "GET_MY_ROW"
, null
, { dataType: text
, success: function(pData){
if (pData == 1) {
clearInterval(myInterval);
alert('Record loaded successfully');
};
}
}
);
The call doesn't really need to be async though, but ok.
Another option would be to implement a "long poll" instead of firing the ajax event every 5 seconds. A long poll will just initiate a call to the server and wait for a response. As long as the server is busy, the client will wait. To achieve this you could use dbms_alert, as suggested in Waiting for a submitted job to finish in Oracle PL/SQL?
You'd signal an alert in the plsql code of the job, and in the ondemand process code register an interest in the alert and use waitone/any with a 60 second timeout. Presto long poll.

Database Backed Work Queue

My situation ...
I have a set of workers that are scheduled to run periodically, each at different intervals, and would like to find a good implementation to manage their execution.
Example: Let's say I have a worker that goes to the store and buys me milk once a week. I would like to store this job and it's configuration in a mysql table. But, it seems like a really bad idea to poll the table (every second?) and see which jobs are ready to be put into the execution pipeline.
All of my workers are written in javascript, so I'm using node.js for execution and beanstalkd as a pipeline.
If new jobs (ie. scheduling a worker to run at a given time) are being created asynchronously and I need to store the job result and configuration persistently, how do I avoid polling a table?
Thanks!
I agree that it seems inelegant, but given the way that computers work something *somewhere* is going to have to do polling of some kind in order to figure out which jobs to execute when. So, let's go over some of your options:
Poll the database table. This isn't a bad idea at all - it's probably the simplest option if you're storing the jobs in MySQL anyway. A rate of one query per second is nothing - give it a try and you'll notice that your system doesn't even feel it.
Some ideas to help you scale this to possibly hundreds of queries per second, or just keep system resource requirements down:
Create a second table, 'job_pending', where you put the jobs that need to be executed within the next X seconds/minutes/hours.
Run queries on your big table of all jobs only once in a longer while, then populate the small table which you query every shorter while.
Remove jobs that were executed from the small table in order to keep it small.
Use an index on your 'execute_time' (or whatever you call it) column.
If you have to scale even further, keep the main jobs table in the database, and use the second, smaller table I suggest, just put that table in RAM: either as a memory table in the DB engine, or in a Queue of some kind in your program. Query the queue at extremely short intervals if you have too - it'll take some extreme use cases to cause any performance issues here.
The main issue with this option is that you'll have to keep track of jobs that were in memory but didn't execute, e.g. due to a system crash - more coding for you...
Create a thread for each of a bunch of jobs (say, all jobs that need to execute in the next minute), and call thread.sleep(millis_until_execution_time) (or whatever, I'm not that familiar with node.js).
This option has the same problem as no. 2 - where you have to keep track job execution for crash recovery. It's also the most wasteful imo - every sleeping job thread still takes system resources.
There may be additional options of course - I hope that others answer with more ideas.
Just realize that polling the DB every second isn't a bad idea at all. It's the most straightforward way imo (remember KISS), and at this rate you shouldn't have performance issues so avoid premature optimizations.
Why not have a Job object in node.js that's saved to the database.
var Job = {
id: long,
task: String,
configuration: JSON,
dueDate: Date,
finished: bit
};
I would suggest you only store the id in RAM and leave all the other Job data in the database. When your timeout function finally runs it only needs to know the .id to get the other data.
var job = createJob(...); // create from async data somewhere.
job.save(); // save the job.
var id = job.id // only store the id in RAM
// ask the job to be run in the future.
setTimeout(Date.now - job.dueDate, function() {
// load the job when you want to run it
db.load(id, function(job) {
// run it.
run(job);
// mark as finished
job.finished = true;
// save your finished = true state
job.save();
});
});
// remove job from RAM now.
job = null;
If the server ever crashes all you have to is query all jobs that have [finished=false], load them into RAM and start the setTimeouts again.
If anything goes wrong you should be able to restart cleanly like such:
db.find("job", { finished: false }, function(jobs) {
each(jobs, function(job) {
var id = job.id;
setTimeout(Date.now - job.dueDate, function() {
// load the job when you want to run it
db.load(id, function(job) {
// run it.
run(job);
// mark as finished
job.finished = true;
// save your finished = true state
job.save();
});
});
job = null;
});
});

Categories

Resources