komron
komron

Reputation: 2277

Typescript Angular Running Background parallel task

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)

Upvotes: 1

Views: 10226

Answers (1)

Heikki Pitkänen
Heikki Pitkänen

Reputation: 38

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.

Upvotes: 1

Related Questions