A little research on the @scheduled of timed tasks in spring

Source: Internet
Author: User
Tags dateformat ticket

Recently done a public number project, the public number will ask the server to ask for a access_token, get the process:

Access_token is the public number's global unique interface invocation credential, and the public number calls each interface using Access_token. Developers need to be properly saved. The Access_token store retains at least 512 character space. The access_token is currently valid for 2 hours and needs to be refreshed periodically, and repeated acquisition will result in the Access_token failure of the last acquisition.

Description of the use and generation of Access_token required by the API call of the public platform:

1, the proposed public number of developers using the central control server to obtain and refresh Access_token, the other business logic server used by the Access_token are from the central control server, should not be refreshed, otherwise prone to conflict, Cause Access_token coverage and affect the business;

2, the current period of validity of Access_token through the return of the expire_in to convey, is currently within 7,200 seconds value. The central control server needs to refresh the new Access_tokenin advance according to this effective time. During the refresh process, the central control server can continue to export the old Access_token, when the public platform backstage will be guaranteed in 5 minutes, the new and old Access_token are available, which ensures a smooth transition of third-party business;

3, the effective time of access_token may be adjusted in the future, so the central control server not only need internal timing active refresh, also need to provide a passive flush access_token interface, so that the business Server in the API call learned that the Access_token has timed out the case , you can trigger the Access_token refresh process.

So the solution is to do a timed task, the service starts the time to obtain tokens, and then every two hours automatically get once. This is easily accomplished with spring's @scheduled annotations:

@Override @Scheduled (fixedrate=1000*60*59*2)     Public voidUpdatetoken () {Try{             for(AppConfig appConfig:SysConfig.AppLists) {token token=Tokenapi.token (Appconfig.wxappid,appconfig.wxappsecret); Appconfig.access_token=Token.getaccess_token (); Ticket Ticket=Ticketapi.ticketgetticket (Token.getaccess_token ()); Appconfig.ticket=Ticket.getticket (); Logger.info ("Access_token:" + token.getaccess_token () + ", Js_api_ticket:" +Ticket.getticket ()); }        }Catch(Exception e) {logger.info ("Refresh Access_token Error"); }    }

Here, you use Fixedrate to specify the time interval (in milliseconds) that the task executes.

Then, because there is only one service number for the project, there is no service number for the test, and local debugging is going to get access_token, which results in the token invalidation of the service-side production environment, and the server's tomcat must be restarted to refresh token. Obviously this is very foolish, and it is not formally put into use, which is obviously unacceptable after it has been put into use.

The solution is to unify an interface to get tokens to the server and, when token fails, execute a Updatetoken method to refresh the token.

=================================================================== Manual Split Line ======================================= =====================

Then I was curious about one thing, that is, when the method of adding @scheduled (fixedrate=1000*60*59*2) is called by other methods, does the scheduled task change ? For example, I call once, then the task is to run according to the previous scheduled time, or will I call after the 2 hours (scheduled interval) will not run again? Baidu Google looked for, including official documents did not give a statement. For this also do not want to see the source code, or write a demo verification under it.

Start by creating a Spring boot project that introduces a Web module (using rest requests to manually invoke timed tasks)

< Dependency >    < groupId >org.springframework.boot</groupId>    <  Artifactid>spring-boot-starter-web</artifactid> </ Dependency >

Project structure:

Service Interface:

 Package Com.xiatingfei.schedule.demo.service;  Public Interface Taskservice {    void  sayhellotask ();}

Service implementation (print once every 10 seconds in the console hello! ):

 PackageCom.xiatingfei.schedule.demo.service.impl;ImportCom.xiatingfei.schedule.demo.service.TaskService;Importorg.springframework.scheduling.annotation.Scheduled;ImportOrg.springframework.stereotype.Service;ImportJava.text.SimpleDateFormat;Importjava.util.Date; @Service Public classTaskserviceimplImplementsTaskservice {Private Static FinalSimpleDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss"); @Override @Scheduled (fixedrate= 10000)     Public voidSayhellotask () {System.out.println ("Hello! Now is "+ Dateformat.format (NewDate ())); }}

Controller:

 PackageCom.xiatingfei.schedule.demo.controller;ImportCom.xiatingfei.schedule.demo.service.TaskService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController, @RestController @requestmapping ("/demo") Public classTriggercontroller {@Autowired taskservice taskservice; @RequestMapping ("/sayhello")     Public voidTriggertask () {taskservice.sayhellotask (); }}

Then add annotations to the timed task in the Springboot startup class @enablescheduling

 PackageCom.xiatingfei.schedule.demo;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.scheduling.annotation.EnableScheduling, @SpringBootApplication @enablescheduling Public classDemoApplication { Public Static voidMain (string[] args) {Springapplication.run (demoapplication.class, args); }}

Launch the app and you can see that the console can print the Hello and time periodically:

When postman sends a request to the server, it calls the scheduled task manually:

Get Http://localhost:8080/demo/sayHello

Results:

you can see that the scheduled task is not affected by the call, or at your own pace for 10 seconds ~ ~

(also, it will be found that spring will initialize the Dispatcherservlet when it first receives the HTTP request, rather than initializing it when the service starts)

A little research on the @scheduled of timed tasks in spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.