Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

java - Schedule a task with a master list updating every 1 hour

I need to create a schedule task every 10 minutes that will process a List that was query in the database.. But that list of Object needs to be updated every 1 hour to get the fresh data. How i can refresh the dataList every 1 hour?

So far here is what i tried, Assuming the run() is the main method:

public class Handler  {
    
    private static final ScheduledExecutorService scheduledExecutorService = ScheduledExecutorService.wrap(
                new ScheduledThreadPoolExecutor(3), "handler-thread-%d");
    
    private void run(DB db) {
        scheduledExecutorService .scheduleAtFixedRate(new Impl(), 1, 10, TimeUnit.MINUTES);
    }
    
    private class Impl implements Runnable {
    
        private List<Object> dataList;

        @Override
        public void run() {
            initialize();
            dataList.forEach(data-> {
                someTask(data);
            });
        }
    
        private void initialize() {
            dataList= new ArrayList<>();
            dataList = getFromDB();
        }
    }
}
question from:https://stackoverflow.com/questions/65846873/schedule-a-task-with-a-master-list-updating-every-1-hour

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

dataList should be shared between all relevant threads. Yet, pay attention you are creating a new list for every iteration, so the object itself is been overriden. I guess you should clear the existing list and use it I steaf of creating a new one (or alternatively use a Reference wrapper).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...