Print "Hello World" Every X Seconds

Print hello world every X seconds

You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.

You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..

Here's an example, which prints Hello World every 5 seconds: -

class SayHello extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}

// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);

Run certain code every n seconds

import threading

def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

How to repeatedly execute a function every x seconds?

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

Executing code every x seconds

Here you are an example for the java.util.Timer:

We need a task to be called by the Timer: MyTimerTask

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample extends TimerTask {

@Override
public void run() {

// Implement your Code here!
}
}

Then we have to schedule a Timer to execute this Task:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 0, 10 * 1000);

The first argument is the Task to be executed.

The second parameter states a delay before the first execution.

The third parameter is the period in milliseconds. (Here: Execute every 10 Seconds!)

Please note that if you want to do things in your GUI with this mechanism you need to use SwingUtilities.invokeLater()


Supplemental after edit:

To use javax.swing.Timer you have to call start() to make the timer run.

How to write a line to end of a file every 'x' seconds

At every iteration, you re-open your file using a FileWriter. By default, it starts writing at the beginning of the file, thus overwriting its contents with always the same "Hello World" string.

If you want to add that sentence to the end, then you want to set the "append" option when instanciating your FileWriter. Also append a line separator each time:

public static void main(String[] args) {
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1000);
ses.scheduleAtFixedRate(new Runnable() {

public void run() {

FileWriter fw = null;
try {
fw = new FileWriter("Test5.txt", true);
} catch (IOException e1) {

e1.printStackTrace();
}

try {
fw.write("Hello World");
fw.write(System.lineSeparator());
} catch (IOException e) {

e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {

e.printStackTrace();
}

}

}, 0, 5, TimeUnit.SECONDS);

}

How to print a string in c language for like 10 seconds?

Maybe use time()

Save the start time in one variable. Have another variable with the current time and keep printing until the difference is what you want.

Like

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(void) {
time_t start = time(NULL); // Get start time
time_t current = start;
while(current - start < 10) { // Check difference
printf("Hello World\n");
// sleep(1); // To limit amount of output if needed
current = time(NULL); // Update current time
}
return 0;
}

For X seconds do some action every Y seconds

Here you go! just put your function call where I am printing!

import time
totalTime = 5
dt = 0.0

while dt <= totalTime:
print(dt)
time.sleep(0.8)
dt += 0.8

How can I do something within a while loop at a particular interval without interrupting the entire loop?

Try to do

t = threading.Timer(5.0, printit)
t.start()

instead of

threading.Timer(5.0, printit).start()

and then, when you want it to stop (after the while loop has finished), do

t.cancel()

Hope this helps!

Edit:

Oh, you need t to be accessible from outside of printit(). You can declare it outside of printit(), or have printit() return it, for example.

Edit 2:

Sorry, there's also the problem that you pass printit() to the timer, where printit() itself is the one who creates the timer, so there's a loop.

Here's how it should be done:

import threading
import sched, time

def printit():
print("Hello, World!")

t = threading.Timer(5.0, printit)
t.start()

x=25
printit()

while x>1:
time.sleep(1)
print(x)
x=x-1

t.cancel()

Edit 3:

With Thread instead of Timer:

import threading
import sched, time

flag = True

def printit():
while(flag):
time.sleep(5)
print("Hello, world!")

t = threading.Thread(target=printit)
t.start()

x=25

while x>1:
time.sleep(1)
print(x)
x=x-1

flag = False


Related Topics



Leave a reply



Submit