Cheng
Cheng

Reputation: 193

Set a timer in R to execute a program

I have a program to execute per 15 seconds, how can I achieve this, the program is as followed:

print_test<-function{
    cat("hello world")
}

Upvotes: 0

Views: 5443

Answers (4)

You also can use like this:

h <- function(i) {
  Sys.sleep(i)
  print("Hello world!")
}

timer <- function(i) {
  while (T) {
    h(i)
  }
} # Timer function

Upvotes: 0

Saksham
Saksham

Reputation: 9380

You can use something like this:

print_test<-function(x)
{
    if(condition)
    {
        Sys.sleep(x);
        cat("hello world");
        print_test(x);
    }
}
print_test(15)

In this, a function is calling itself after the seconds passed as argument given the condition evaluates to true.

Upvotes: 0

Frash
Frash

Reputation: 728

What I use for executing same code block every 15 seconds:

interval = 15
x = data.frame()

repeat {
  startTime = Sys.time()
  x = rbind.data.frame(x, sum(data)) #replace this line with your code/functions
  sleepTime = startTime + interval - Sys.time()
  if (sleepTime > 0)
    Sys.sleep(sleepTime)
}

x and data are dummy which you need to replace accordingly. This will execute indefinitely until stopped by user. If you need to stop and start at specific times then you need a for loop instead of 'repeat`.

Hope this helps.

Upvotes: 4

MichaelVE
MichaelVE

Reputation: 1344

You can do something like this:

print_test<-function(x)
{ 
Sys.sleep(x)
cat("hello world")
}

print_test(15)

If you want to execute it for a certain amount of iterations use to incorporate a 'for loop' in your function with the number of iterations.

Upvotes: 1

Related Questions