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
Related
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;
How can I achieve a loop like this:
foobar.each(function (model, j) {
// asynchrounous call etc. {in here bool get set to true}
// outside all asynchronous calls
// wait till bool is true, without stopping anything else except the loop to the top of
the _.each
})
I asked a similar question yesterday. But it got marked as a duplicate when it wasn't the same case. Their solution did not achieve the same thing. Also generator functions were suggested which looked like it would work. But I can't use them with ecmascript 5
I've tried busy loops and set time out but they don't seem to work either
I've also tried this:
goto();
function goto() {
if (foo === true) {
//return true; /*I've tried with and without the return because the loops
doesn't need a return*/
} else {
goto();
}
}
What happens with the goto() method is it breaks. Giving me the right results for the first iterations then execution seems to stop altogether. 'foo' always gets set to true in normal execution though.
What you could do is implement a foreach yourself, where you execute your condition, and then on success callback go to the next item (but meanwhile the rest of the code will keep running.
var iteration = 0 //count the iteration of your asynchronous process
//start looping
loop(iteration)
function loop(iteration){
var model = foobar[iteration];
//exit your loop when all iterations have finished (assuming all foobar items are not undefined)
if (foobar[iteration] === undefined){
return;
}
//do what you want
//on success callback
iteration++;
loop(iteration);
//end success callback
}
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.
-define(INTERVAL, 1000).
init([]) ->
Timer = erlang:send_after(?INTERVAL, self(), tick),
{ok, Timer}.
handle_info(tick, OldTimer) ->
erlang:cancel_timer(OldTimer),
io:format("Tick ~w~n", [OldTimer]),
Timer = erlang:send_after(?INTERVAL, self(), tick).
{noreplay, Timer}.
start_clock() ->
{_, Timer} = init([]),
spawn(clock, handle_info, [tick, Timer]).
My codes is as above, but the output is not what I want.
How can I integrate init() and handle_info() into the main function(start_clock)?
In the timer module, the function apply_interval(Time, Module, Function, Arguments) executes Module:Function(Arguments) every interval of Time. It takes care of spawning a process, returns a reference to allow a cancellation later.
You also can have a look at send_interval(Time, Pid, Message) in the same library.
You can also implement a simple loop like:
loop(Args,Tick) when is_integer(Tick), Tick >= 0 ->
receive
stop -> stopped
after
Tick ->
do_something(Args),
{NewArgs,NewTick} = new_args(Args,Tick),
loop(NewArgs,NewTick)
end.
it is not a realtime timer, but the function new_args(Args,Tick) can help to correct the deviation due to process scheduling.
I think you need something like this:
start_timer() ->
gen_server:start_link({local, clock}, ?MODULE, [], []).
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>