admin管理员组

文章数量:1022415

I have to create a ponent in angular that clean the data in the database (via a service call) every hour and displays the last clean time in HTML. Couple of question

  1. When we route from one ponent to another, does the ponent get auto destroyed and lose all its data?
  2. Is it possible to persist data and use it in the future?
@Component({
  selector: 'demo-app',
  template:`
  <button (click)="clearData()"></button>
  <h2>Last synced time: {{ time }}</h2>
  `
})
export class AppComponent {
 
  public time;
 
  constructor(private demoService: DemoService) { }

  // ----> this should be triggered every hour <----
  clearData() {
    this.demoService.deleteData()
      .subscribe((lastCleanTime) => {this.time = lastCleanTime;});
    }
}

I have to create a ponent in angular that clean the data in the database (via a service call) every hour and displays the last clean time in HTML. Couple of question

  1. When we route from one ponent to another, does the ponent get auto destroyed and lose all its data?
  2. Is it possible to persist data and use it in the future?
@Component({
  selector: 'demo-app',
  template:`
  <button (click)="clearData()"></button>
  <h2>Last synced time: {{ time }}</h2>
  `
})
export class AppComponent {
 
  public time;
 
  constructor(private demoService: DemoService) { }

  // ----> this should be triggered every hour <----
  clearData() {
    this.demoService.deleteData()
      .subscribe((lastCleanTime) => {this.time = lastCleanTime;});
    }
}
Share Improve this question edited Oct 18, 2021 at 17:14 Dan asked Oct 18, 2021 at 4:52 DanDan 7711 gold badge20 silver badges35 bronze badges 2
  • 1 use timer to trigger clearData and use local storage to store that data – Rishab Vaigankar Commented Oct 18, 2021 at 5:02
  • Yeah, I was thinking the same, but checking if there is a better solution. – Dan Commented Oct 18, 2021 at 5:53
Add a ment  | 

4 Answers 4

Reset to default 5

I don't prefer to do that through the client-side, it's okay to add a button to that run it, just imagine these cases:

  • You have 3 users, so this task will run about 3 times every hour, what about more?
  • You have no users, so the task will never run.

I prefer to do that from the server-side, and you can update the time through an API to get the latest time or you can add a WebSocket to make it always updated.

1 Yes, Component data get erased when you navigated from one ponent to another. if you want to do something before the ponent getting destroy you can use the ngOnDestroy Lifecycle method of the ponent.

2 you can use the service to store data while navigating between ponents.

Ok, instead of getting a trigger from user, it will be easier to run a database query internally every hour How to schedule a database task? Please refer to this link.

Ans 1. The ponent scope is only available till it is present in DOM so yes it will be destroyed once it is out of scope or DOM.

Ans 2. You can maintain data using models or state or local variables.

A database cleanup task should indeed be run on the server side periodically. In Java projects where I have participated, we have done similar tasks with Tomcat or Jetty using ServletContextListener. Other servers, e.g. node, have their own mechanisms of course.

You create a class implementing this interface, whose methods get called when your servlet is started or destroyed. In the startup method you create a thread that cleans the db up in a loop every hour, until the servlet is destroyed:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class DBCleanupContextListener implements ServletContextListener
{
    private ExecutorService threadPool;
    private DBCleanupTask dbCleanupTask;

    public DBCleanupContextListener()
    {
        threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        dbCleanupTask = new DBCleanupTask();
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0)
    {
        threadPool.execute(dbCleanupTask);

        // submit additional tasks here if needed...
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0)
    {
        dbCleanupTask.shutdown();
        threadPool.shutdown();
    }

    class DBCleanupTask implements Runnable
    {
        boolean finished = false;
        
        @Override
        public void run()
        {
            while (!finished)
            {
                
                System.out.println("db cleanup code goes here ....");
                
                try
                {
                    Thread.sleep(60 * 60 * 1000); // sleeps 1 hour = 60min*60sec*1000ms
                }
                catch (InterruptedException e)
                {
                    finished = true;
                }
            }
        }
    
        public void shutdown()
        {
            finished = true;
        }
        
    }
}

I have run this code with Tomcat, Jetty and Spring Boot. Theoretically it should run on any JavaEE server, but you need to research how to configure the servlet. On Tomcat for example it needs to be added to the web.xml, as described here:

<web-app ...>
<listener>
    <listener-class>
            .example.DBCleanupContextListener 
        </listener-class>
</listener>
</web-app>

I have to create a ponent in angular that clean the data in the database (via a service call) every hour and displays the last clean time in HTML. Couple of question

  1. When we route from one ponent to another, does the ponent get auto destroyed and lose all its data?
  2. Is it possible to persist data and use it in the future?
@Component({
  selector: 'demo-app',
  template:`
  <button (click)="clearData()"></button>
  <h2>Last synced time: {{ time }}</h2>
  `
})
export class AppComponent {
 
  public time;
 
  constructor(private demoService: DemoService) { }

  // ----> this should be triggered every hour <----
  clearData() {
    this.demoService.deleteData()
      .subscribe((lastCleanTime) => {this.time = lastCleanTime;});
    }
}

I have to create a ponent in angular that clean the data in the database (via a service call) every hour and displays the last clean time in HTML. Couple of question

  1. When we route from one ponent to another, does the ponent get auto destroyed and lose all its data?
  2. Is it possible to persist data and use it in the future?
@Component({
  selector: 'demo-app',
  template:`
  <button (click)="clearData()"></button>
  <h2>Last synced time: {{ time }}</h2>
  `
})
export class AppComponent {
 
  public time;
 
  constructor(private demoService: DemoService) { }

  // ----> this should be triggered every hour <----
  clearData() {
    this.demoService.deleteData()
      .subscribe((lastCleanTime) => {this.time = lastCleanTime;});
    }
}
Share Improve this question edited Oct 18, 2021 at 17:14 Dan asked Oct 18, 2021 at 4:52 DanDan 7711 gold badge20 silver badges35 bronze badges 2
  • 1 use timer to trigger clearData and use local storage to store that data – Rishab Vaigankar Commented Oct 18, 2021 at 5:02
  • Yeah, I was thinking the same, but checking if there is a better solution. – Dan Commented Oct 18, 2021 at 5:53
Add a ment  | 

4 Answers 4

Reset to default 5

I don't prefer to do that through the client-side, it's okay to add a button to that run it, just imagine these cases:

  • You have 3 users, so this task will run about 3 times every hour, what about more?
  • You have no users, so the task will never run.

I prefer to do that from the server-side, and you can update the time through an API to get the latest time or you can add a WebSocket to make it always updated.

1 Yes, Component data get erased when you navigated from one ponent to another. if you want to do something before the ponent getting destroy you can use the ngOnDestroy Lifecycle method of the ponent.

2 you can use the service to store data while navigating between ponents.

Ok, instead of getting a trigger from user, it will be easier to run a database query internally every hour How to schedule a database task? Please refer to this link.

Ans 1. The ponent scope is only available till it is present in DOM so yes it will be destroyed once it is out of scope or DOM.

Ans 2. You can maintain data using models or state or local variables.

A database cleanup task should indeed be run on the server side periodically. In Java projects where I have participated, we have done similar tasks with Tomcat or Jetty using ServletContextListener. Other servers, e.g. node, have their own mechanisms of course.

You create a class implementing this interface, whose methods get called when your servlet is started or destroyed. In the startup method you create a thread that cleans the db up in a loop every hour, until the servlet is destroyed:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class DBCleanupContextListener implements ServletContextListener
{
    private ExecutorService threadPool;
    private DBCleanupTask dbCleanupTask;

    public DBCleanupContextListener()
    {
        threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        dbCleanupTask = new DBCleanupTask();
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0)
    {
        threadPool.execute(dbCleanupTask);

        // submit additional tasks here if needed...
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0)
    {
        dbCleanupTask.shutdown();
        threadPool.shutdown();
    }

    class DBCleanupTask implements Runnable
    {
        boolean finished = false;
        
        @Override
        public void run()
        {
            while (!finished)
            {
                
                System.out.println("db cleanup code goes here ....");
                
                try
                {
                    Thread.sleep(60 * 60 * 1000); // sleeps 1 hour = 60min*60sec*1000ms
                }
                catch (InterruptedException e)
                {
                    finished = true;
                }
            }
        }
    
        public void shutdown()
        {
            finished = true;
        }
        
    }
}

I have run this code with Tomcat, Jetty and Spring Boot. Theoretically it should run on any JavaEE server, but you need to research how to configure the servlet. On Tomcat for example it needs to be added to the web.xml, as described here:

<web-app ...>
<listener>
    <listener-class>
            .example.DBCleanupContextListener 
        </listener-class>
</listener>
</web-app>

本文标签: javascriptHow to schedule a task in AngularStack Overflow