1

While writing an app in Angular 4 there arose a need to execute some method (task|process|job) in background which would run paralelly to other task in background no matter what the user is currently doing, which component he/she is interacting with. And execute that method so that it doesn't block others.

That background method is realisation of polling, so it periodically by determined interval sends requests to server asking for current status of some object.

Ideally it is better to know how to write collection of such methods which in some interval send requests to server to ask for status of some obects. And none of them blocks others.

My question is what is the best and correct way to write such method/collection of methods.

Thanks in advance for spending your time on this!

P.S. : Turns out i mixed parallelism & concurrency terms. Actually wherever i mention parallelism in this post - i mean concurrency.

Concurrency is when two or more tasks can start, run, and complete in overlapping time periods. It doesn't necessarily mean they'll ever both be running at the same instant. Eg. multitasking on a single-core machine.

Parallelism is when tasks literally run at the same time, eg. on a multicore processor.

RichieHindle (c)

1
  • Search for Web Worker Commented Oct 31, 2017 at 9:11

1 Answer 1

1

I'm not sure if it is best practice, but I'm running an asynchronous play() function to play a simulation in my project. It has a while(true) loop in it and that loop then calls socket.io to tell server to send lines from the simulation to client and update the view according to them.

Adapted to your case:

var updateEveryMS = 1000;  

async poll() {
  while (true) {
    // code to poll server and update models and view ...
  await this.sleep(updateEveryMs);
}

sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

and then call poll() in ngAfterViewInit()

ngAfterViewInit() {
  poll();
}

to start it after the page has loaded.

Sign up to request clarification or add additional context in comments.

3 Comments

Well Thanks, i think it will work but it's not the best solution im my opinion
@komron Indeed, now that I think of it, it's a bit clumsy. Maybe you could put into your ngAfterViewInit something like setInterval( () => { poll_server().then( (answer) => { update_view(answer); } ); } , updateEveryMs); where poll_server is a function that returns a promise that resolves the answer from the server.
Also using observables for this i think also is not bad solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.