-1

I need to automate my API cases, In which the token which I used to run API's get expired after every one hr. So i need to regenerate the token using specific method. How can i run this particular method after each hour when ever i run my automation?

lokesh
  • 49
  • 10

3 Answers3

1

you can simply use EnableScheduling for it

Something like this should do the trick (adapted from the Javadoc for @EnableScheduling):

@Configuration
@EnableScheduling
public class MyAppConfig implements SchedulingConfigurer {

    @Autowired
    Environment env;

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
        taskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override public void run() {
                        myBean().getSchedule();
                    }
                },
                new Trigger() {
                    @Override public Date nextExecutionTime(TriggerContext triggerContext) {
                        Calendar nextExecutionTime =  new GregorianCalendar();
                        Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
                        nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
                        nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("myRate", Integer.class)); //you can get the value from wherever you want
                        return nextExecutionTime.getTime();
                    }
                }
        );
    }
}

another way just put @Scheduled(cron = "0 0 0/1 1/1 * ?") before your api call method like this :

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {

    long now = System.currentTimeMillis() / 1000;
    System.out.println(
      "schedule tasks using cron jobs - " + now);
}
Sandip Solanki
  • 704
  • 1
  • 8
  • 15
0

You can try the sleep method.

new Thread(()->{
    while(true) {
        method(); //your method
        Thread.sleep(3600000);
    }
}).start();
Ben
  • 196
  • 15
0

You can use something like a cron with the method "scheduleAtFixedRate"

How to create a Java cron job

B.vlt
  • 16
  • 4