Home > Software design >  How to schedule a periodic background work to activate at fixed times?
How to schedule a periodic background work to activate at fixed times?

Time:04-02

I want to push a notification every 12 hours at fixed times (lets say for an example, 9am and 9pm, every day). This is my current doWork() code:

  @NonNull
    @Override
    public Result doWork() {

        database.child("business_users").child(currentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                user = snapshot.getValue(BusinessUser.class);
                if(user.isNotifications()==true)
                {
                    if(user.getRatingsCount() > user.getLastKnownRC())
                    {
                        theDifference = user.getRatingsCount() - user.getLastKnownRC();
                        notification();
                    }
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        Log.i("BackgroundWork" , "notif sent");
        return Result.success();
    }

`

and this is the work creation code:

public void FirstTimeWork ()
     {
         PeriodicWorkRequest myWorkRequest =
                 new PeriodicWorkRequest.Builder(BackgroundWork.class, 12, TimeUnit.HOURS)
                         .setInitialDelay(1, TimeUnit.DAYS)
                         .addTag("notif")
                         .build();
     }

I saw some people doing it with calendar but I don't understand how it works.

CodePudding user response:

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file.

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

The @Scheduled annotation is used to trigger the scheduler for a specific time period.

@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() throws Exception {
}

The following is a sample code that shows how to execute the task every minute starting at 9:00 AM and ending at 9:59 AM, every day

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(cron = "0 * 9 * * ?")
   public void cronJobSch() {
      System.out.println(LocalDateTime.now());
   }
}

CodePudding user response:

You can use class Timer. Then, your background job must be implemented in a subclass to TimerTask in the overridden method public void run(), e.g.:

public class BackgroundWork extends TimerTask {
    @Override
    public void run() {
        // Do your background work here
        Log.i("BackgroundWork" , "notif sent");
    }
}

You can schedule this job as follows:

// void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Date date = new Date( 2022, 04, 02, 9, 00 );
(new Timer()).scheduleAtFixedRate(new BackgroundWork(), date, 43200000L);

Timer starts a new thread to execute this job. You can cancel it, if necessary.

  • Related