Loop every 10 second
My try. (Almost) perfectly POSIX. Works on both POSIX and MSVC/Win32 also.
#include <stdio.h>
#include <time.h>
const int NUM_SECONDS = 10;
int main()
{
int count = 1;
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
printf("Gran = %ld\n", NUM_SECONDS * CLOCKS_PER_SEC);
while(true)
{
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if(time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
{
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
printf("%d\n", count);
count++;
}
printf("DebugTime = %f\n", time_counter);
}
return 0;
}
This way you can also have the control on each iteration, unlike the sleep()-based approach.
This solution (or the same based on high-precision timer) also ensures that there is no error accumulation in timing.
EDIT: OSX stuff, if all else fails
#include <unistd.h>
#include <stdio.h>
const int NUM_SECONDS = 10;
int main()
{
int i;
int count = 1;
for(;;)
{
// delay for 10 seconds
for(i = 0 ; i < NUM_SECONDS ; i++) { usleep(1000 * 1000); }
// print
printf("%d\n", count++);
}
return 0;
}
How to make my function loop every x second in javascript
Problem with the current implementation is that it uses asynchronous requests which may take more than 10 seconds(can't predict when the request is served).
The method setInterval
will execute the myFunction
irrespective of the previous requests were completed or not.
As a result next request will queue up to be executed. So you get it is sometimes executed after 5 sec and sometimes after 8 and so on.
You should use setTimeout()
to recursively invoke the method instead of using setInterval
function myFunction() {
$.getJSON("URL", function (data) {
$.getJSON("URL", function (data2) {
//Your existing code
//Schedule it be executed after x * 1000 milliseconds
setTimeout(myFunction, 10000);
});
});
}
myFunction();
How to run timer every x seconds within a loop without stalling the loop?
Use datetime.timedelta
to check if enough time passed:
import datetime
i = 0
start = datetime.datetime.now()
last = start
while True:
my_function()
i += 1
now = datetime.datetime.now()
if now - last > datetime.timedelta(seconds=10):
last = now
print('Elapsed: ' + str(now-start) + ' | Iteration #' + str(i))
PHP: Execute a function inside a while loop every 10 seconds
I'm using now a setInterval() function to check:
let interval = setInterval( function () {
//If max time of 5 minutes exceeded (5 * 60000) I leave the interval
if ( new Date().getTime() - startTime > 300000 ) {
clearInterval( interval );
}
//Here I'm doing my AJAX request to check the payment status
}, 5000 ); //<- Execute every 5 seconds
This works great for me and is simple
Loop every five seconds in Javascript
var time = 1;
var interval = setInterval(function() {
if (time <= 3) {
alert(time);
time++;
}
else {
clearInterval(interval);
}
}, 5000);
you can simply create an interval and kill it after the 3rd time
How do I end a loop within a loop after 10 seconds?
Another way of running a while loop for 10 seconds is using datetime
module.
import datetime
start_time = datetime.datetime.now()
#end time is 10 sec after the current time
end_time = start_time + datetime.timedelta(seconds=10)
#Run the loop till current time exceeds end time
while end_time > datetime.datetime.now():
#do stuff
An advantage here is you can also define time intervals in minutes and hours using the datetime.timedelta function
How to run program in R every 10 seconds without Scheduler?
Use Sys.sleep()
i = 1
while(TRUE){
if (i %% 11 == 0){
#write.table() #But maybe you would want to write results
#to a table after certain number of iteration
break #A condition to break out of the loop
}
print(i) #Run your code
Sys.sleep(time = 1) #Time in seconds
i = i + 1
}
Related Topics
Is Returning Local Static Object Thread Safe for Pre-C++11 Compilers
Stateful Functors & Stl:Undefined Behaviour
Cocreateinstance Returning E_Nointerface Even Though Interface Is Found
Using Boost Tokenizer Escaped_List_Separator with Different Parameters
Conversion from 'Myitem*' to Non-Scalar Type 'Myitem' Requested
Undefined Symbols in Crypto++/iOS 64-Bit Project
How-To Ensure That Compiler Optimizations Don't Introduce a Security Risk
Cudamalloc of a Structure and an Element of Same Structure
Under What Circumstances Is It Advantageous to Give an Implementation of a Pure Virtual Function
How to Calculate Offset of a Class Member at Compile Time
Cost of Using Std::Map with Std::String Keys VS Int Keys
Does Class/Function Order Matter in C++
Send Binary File Over Tcp/Ip Connection
Why "Long Int" Has Same Size as "Int"? Does This Modifier Works at All