So basically I made a timer command using ms.js, and when i use the command /timer 5s, it responds with the timer has ended directly after without actually waiting the 5 seconds, any help?
case 'timer':
let time = ms(args[1])
setTimeout(() => {
message.channel.send('Your timer has now ended.')
}, ms(time));
break;
first of all check the value of time variable. if that is ok then modify your code like below. and be careful that the setTimeout use millisecond as time parameter
case 'timer':
let time = ms(args[1])
setTimeout(() => {
message.channel.send('Your timer has now ended.')
},time);
break;
Related
In Node.js I can set the interval that a certain event should be triggered,
function intervalFunc() {
console.log('whelp, triggered again!');
}
setInterval(intervalFunc, 1500);
However the interface for Tokio's interval is a bit more complex. It seems to be a something to do with a much more literal definition of an interval, and rather than calling a function at an interval, it simply stalls the thread until the time passes (with .await).
Is there a primitive in Tokio that calls a function "every x seconds" or the like? If not, is there an idiom that has emerged to do this?
I only need to run one function on a recurring interval... I don't care about other threads either. It's just one function on Tokio's event loop.
Spawn a Tokio task to do something forever:
use std::time::Duration;
use tokio::{task, time}; // 1.3.0
#[tokio::main]
async fn main() {
let forever = task::spawn(async {
let mut interval = time::interval(Duration::from_millis(10));
loop {
interval.tick().await;
do_something().await;
}
});
forever.await;
}
You can also use tokio::time::interval to create a value that you can tick repeatedly. Perform the tick and call your function inside of the body of stream::unfold to create a stream:
use futures::{stream, StreamExt}; // 0.3.13
use std::time::{Duration, Instant};
use tokio::time; // 1.3.0
#[tokio::main]
async fn main() {
let interval = time::interval(Duration::from_millis(10));
let forever = stream::unfold(interval, |mut interval| async {
interval.tick().await;
do_something().await;
Some(((), interval))
});
let now = Instant::now();
forever.for_each(|_| async {}).await;
}
async fn do_something() {
eprintln!("do_something");
}
See also:
How can I run a set of functions concurrently on a recurring interval without running the same function at the same time using Tokio?
I am still a rust/tokio beginner, but I did find this solution helpful for myself:
use std::time::Duration;
use tokio::time;
use tokio_stream::wrappers::IntervalStream;
#[tokio::main]
async fn main() {
let mut stream = IntervalStream::new(time::interval(Duration::from_secs(1)));
while let Some(_ts) = stream.next().await {
println!("whelp, triggered again!");
}
}
Please note that _ts holds the execution timestamp.
I have the following test:
testHarness.processElement2(new StreamRecord<>(element1));
testHarness.processElement1(new StreamRecord<>(new Tuple2<>(id, element2)));
testHarness.setProcessingTime(1); //let's assume it's the correct time for the timer inside the function
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult)); //this one is passed
testHarness.setProcessingTime(2); // setting second timer which will trigger different timer
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult2)); //fails cause output has expectedResult & expectedResult2
Why TestHarness is not clearing it's elements once we call getOutput()? Could this functionality be achieved somehow?
This can be achieved by calling clear() on the output :
testHarness.processElement2(new StreamRecord<>(element1));
testHarness.processElement1(new StreamRecord<>(new Tuple2<>(id, element2)));
testHarness.setProcessingTime(1); //let's assume it's the correct time for the timer inside the function
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult)); // Pass
testHarness.getOutput().clear();
testHarness.setProcessingTime(2); // setting second timer which will trigger different timer
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult2)); // Pass
I want to finish the loop or limit messages.
I dont know what to do to stop the loop.
please help
For example I want to do
let timer = setInterval(function(){
if(command = "loop")
message.channel.send("test")
}, sec * 1000)
if(command = "stoploop")
//i need example to stopping the loop
Use clearInterval() to stop a running interval.
let timer = setInterval(function() {
if(command === "loop")
message.channel.send("test")
}, sec * 1000)
if(command === "stoploop") {
clearInterval(timer);
}
Please keep in mind that sending a message to a channel every second is every abusive to Discord's API. Doing such behavior for too long will probably make Discord ban your bot because of API abuse.
I have this RxSwift code in swift 3
let bag:DisposeBag = DisposeBag()
var sig:Observable<Int>!
sig = Observable<Int>.interval(1.0, scheduler: MainScheduler.instance)
sig.subscribe(onNext: { (milsec) in
print("Mil: \(milsec)")
}).addDisposableTo(bag)
i run this code when button tapped, but its not print anything on console.
DisposeBag will dispose of your subscription once it goes out of scope. In this instance, it'll be right after the call to subscribe, and it explains why you don't see anything printed to the console.
Move the definition of dispose bag to the class creating the subscription and everything should work fine.
class MyViewController: UIViewController {
let bag:DisposeBag = DisposeBag()
dynamic func onButtonTapped() {
var sig:Observable<Int>!
sig = Observable<Int>.interval(1.0, scheduler: MainScheduler.instance)
sig.subscribe(onNext: { (sec) in
print("Sec: \(sec)")
}).addDisposableTo(bag)
}
}
On a side note, interval expects an interval in seconds, so it will only tick every seconds as oposed to milliseconds.
I have searched up so many sites on Google to try and get this to work but NO ONE seems to have this anywhere , and if they do it's just NOT working with my program... What I am trying to achieve is to have a player recoil that when the player gets hit, he has a "x" amount of time between getting hit the first time and the second time.
So I have a Boolean "hit" = false and when he gets hit, it changes to true. Which means he can't get hit again until it's changed to false again.
So I'm trying to set up a function in my program to set a "timer" for "x" amount of seconds IF hit = true and once that timer hits "x" amount of seconds, hit will get switched back to false.
Anyone have any ideas?
Thanks!!
A simple option is to manually keep track of time using millis().
You would use two variables:
one to store elapsed time
one to store the wait/delay time you need
In the draw() method you would check if the difference between the current time (in millis.) and the previously stored time is greater(or equal) to the delay.
If so, this would be your cue to do whatever based on the delay chosen and update the stored time:
int time;
int wait = 1000;
void setup(){
time = millis();//store the current time
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
println("tick");//if it is, do something
time = millis();//also update the stored time
}
}
Here's a slight variation the updates a 'needle' on screen:
int time;
int wait = 1000;
boolean tick;
void setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
Depending on your setup/needs, you may choose to wrap something like this into a class that can be reused. This is a basic approach and should work with the Android and JavaScript versions as well (although in javascript you've got setInterval()).
If you're interested in using Java's utilities, as FrankieTheKneeMan suggested, there is a TimerTask class available and I'm sure there are plenty of resources/examples out there.
You can run a demo bellow:
var time;
var wait = 1000;
var tick = false;
function setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
function draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>