Springboot定时任务的使用

Springboot定时任务的使用Spring提供了@Scheduled注解用于定时任务。也就是说一般需求可以无需第三方定时任务。开启定时任务启动类加@EnableScheduling开启定时任务@SpringBootApplication@EnableScheduling //开启定时任务public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); }}执行方法@Componentpublic class Jobs { //表示方法执行完成后5秒 @Scheduled(fixedDelay = 5000) public void fixedDelayJob() throws InterruptedException { System.out.println("fixedDelay 每隔5秒" + new Date()); } //表示每隔3秒 @Scheduled(fixedRate = 3000) public void fixedRateJob() { System.out.println("fixedRate 每隔3秒" + new Date()); } //表示每天8时30分0秒执行 @Scheduled(cron = "0 0,30 0,8 ? * ? ") public void cronJob() { System.out.println(new Date() + " ...>>cron"); }}第三种使用cron表达式可上网搜在线cron表达式,选择时间会自动生成,cron说明* 第一位,表示秒,取值0-59* 第二位,表示分,取值0-59* 第三位,表示小时,取值0-23* 第四位,日期天/日,取值1-31* 第五位,日期月份,取值1-12* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思 另外:1表示星期天,2表示星期一。* 第7为,年份,可以留空,取值1970-2099(*)星号:可以理解为每的意思,每秒,每分,每天,每月,每年...(?)问号:问号只能出现在日期和星期这两个位置。(-)减号:表达一个范围,如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12(,)逗号:表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期一,星期二,星期四(/)斜杠:如:x/y,x是开始值,y是步长,比如在第一位(秒) 0/15就是,从0秒开始,每15秒,最后就是0,15,30,45,60 另:*/y,等同于0/y举例0 0 3 * * ? 每天3点执行0 5 3 * * ? 每天3点5分执行0 5 3 ? * * 每天3点5分执行,与上面作用相同0 5/10 3 * * ? 每天3点的 5分,15分,25分,35分,45分,55分这几个时间点执行0 10 3 ? * 1 每周星期天,3点10分 执行,注:1表示星期天 0 10 3 ? * 1#3 每个月的第三个星期,星期天 执行,#号只能出现在星期的位置开启异步任务在类上加@EnableAsync注解@SpringBootApplication@EnableScheduling //开启定时任务@EnableAsync //开启异步public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); }}异步执行,很简单在方法上加@Async注解即可 @Async @Scheduled(cron = "0 0,30 0,8 ? * ? ") public void cronJob() { System.out.println(new Date() + " ...>>cron"); }基于接口以上基于注解可能不灵活,有时将cron表达式存储在数据库就无法执行了,可以使用接口实现。依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencies> <dependency><!--添加Web依赖 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><!--添加MySql依赖 --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency><!--添加Mybatis依赖 配置mybatis的一些初始化的东西--> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency><!-- 添加mybatis依赖 --> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> <scope>compile</scope> </dependency> </dependencies>执行本地MySQL创建表且插入一条数据DROP DATABASE IF EXISTS `socks`;CREATE DATABASE `socks`;USE `SOCKS`;DROP TABLE IF EXISTS `cron`;CREATE TABLE `cron` ( `cron_id` varchar(30) NOT NULL PRIMARY KEY, `cron` varchar(30) NOT NULL );INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');具体代码:@Component@Configuration //1.主要用于标记配置类,兼备Component的效果。@EnableScheduling // 2.开启定时任务public class DynamicScheduleTask implements SchedulingConfigurer { @Mapper public interface CronMapper { @Select("select cron from cron limit 1") public String getCron(); } @Autowired //注入mapper @SuppressWarnings("all") CronMapper cronMapper; /** * 执行定时任务. */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask( //1.添加任务内容(Runnable) () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()), //2.设置执行周期(Trigger) triggerContext -> { //2.1 从数据库获取执行周期 String cron = cronMapper.getCron(); //2.2 合法性校验. if (StringUtils.isEmpty(cron)) { // Omitted Code .. } //2.3 返回执行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); }}参考:https://www.cnblogs.com/qdhxhz/p/9058418.htmlhttps://www.mmzsblog.cn/articles/2019/08/08/1565247960802.html

Java比较器Comparator进行排序及获取最大最小值

Java比较器Comparator使用/获取最大最小值Comparable:强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的compareTo方法 被称为它的自然比较方法。只能在类中实现compareTo()一次,不能经常修改类的代码实现自己想要的排序。实现 此接口的对象列表(和数组)可以通过Collections.sort(和Arrays.sort)进行自动排序,对象可以用作有序映射中 的键或有序集合中的元素,无需指定比较器。 Comparator:强行对某个对象进行整体排序。可以将Comparator 传递给sort方法(如Collections.sort或 Arrays.sort),从而允许在排序顺序上实现精确控制。还可以使用Comparator来控制某些数据结构(如有序set或 有序映射)的顺序,或者为那些没有自然顺序的对象collection提供排序。Comparator使用 ArrayList<Integer> list = new ArrayList<Integer>();//采用工具类 完成 往集合中添加元素 Collections.addAll(list, 5, 222, 1, 2);//排序方法 Collections.sort(list);// 输出排序后值 第一个最小 末位最大 System.out.println(list);//[1, 2, 5, 222]//为对象排序 ArrayList<String> list1 = new ArrayList<String>(); list1.add("cba"); list1.add("abc"); list1.add("bca"); Collections.sort(list1, new Comparator<String>() { @Override// 第一个参数代表较小的 第二个较大 public int compare(String o1, String o2) { return o1.charAt(0) - o2.charAt(0); } });// Lamada改写 Collections.sort(list1, (o1, o2) -> o1.charAt(0) - o2.charAt(0)); Collections.sort(list1, Comparator.comparingInt(o -> o.charAt(0))); System.out.println(list1);//[abc, bca, cba]Comparable使用Student实体类import lombok.AllArgsConstructor;import lombok.Data;@Data@AllArgsConstructorpublic class Student implements Comparable<Student> { private String name; private int age; @Override public int compareTo(Student o) { return this.age - o.age;//升序 }}或者用if判断重写 @Override public int compareTo(Student o) { //升序 if (this.age > o.age) { return 1; } else if (this.age < o.age){ return -1; } else{ return 0; } }测试// 创建四个学生对象 存储到集合中 ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student("rose", 18)); list.add(new Student("jack", 16)); list.add(new Student("mark", 16)); list.add(new Student("mona", 20));/*让学生 按照年龄排序 升序*/ Collections.sort(list);//要求 该list中元素类型 必须实现比较器Comparable接口 for (Student student : list) { System.out.println(student); }stream获取最大/小值ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 2, 5, 3, 8, 7, 9);Integer max = list.stream().max(Integer::compare).get();Integer min = list.stream().min(Integer::compare).get();System.out.println("最大" + max + ",最小" + min); //最大9,最小2针对与于对象,例如上述Student获取最大年龄跟最小年龄ArrayList<Student> list = new ArrayList<Student>();list.add(new Student("rose", 18));list.add(new Student("jack", 16));list.add(new Student("mark", 16));list.add(new Student("bob", 27));list.add(new Student("mona", 20));Student max = list.stream().max(Student::compareTo).get();Student min = list.stream().min(Student::compareTo).get();System.out.println(max);System.out.println(min);但是如果没有继承Comparable接口重写compareTo的话,就得代码比较年龄了 ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student("rose", 18)); list.add(new Student("jack", 16)); list.add(new Student("mark", 15)); list.add(new Student("bob", 27)); list.add(new Student("mona", 20));// 取最大年龄 这里同样用Comparator Student max = list.stream().max(new Comparator<Student>() { @Override public int compare(Student a, Student b) { if (a.getAge() > b.getAge()) { return 1; } else { return -1; } } }).get();// 取最小年龄 取较大值中最小值 这里也可以用max 不过就要将>改为< Student min = list.stream().min((a, b) -> { if (a.getAge() > b.getAge()) { return 1; } else { return -1; } }).get();// Lamada简写 Student max1 = list.stream().max((a, b) -> a.getAge()-b.getAge()).get(); Student max2 = list.stream().max(Comparator.comparingInt(Student::getAge)).get();// 若跟参数a b顺序不对应的话无法简写成comparingInt 但max这时就成取最小值; Student min1 = list.stream().max((a, b) -> b.getAge()-a.getAge()).get(); Student min2 = list.stream().min((a, b) -> a.getAge()-b.getAge()).get(); System.out.println(min); System.out.println(min1); System.out.println(min2); System.out.println(max); System.out.println(max1); System.out.println(max2);对double等类型比较在Student实体类中加入Double hign身高属性,直接调用Comparator.comparingDouble方法,或者直接使用Comparator.comparing也可以。// 打印最高的学生 Student studentMax = list.stream().max(Comparator.comparingDouble(Student::getHign)).get(); Student studentMin = list.stream().min(Comparator.comparingDouble(Student::getHign)).get(); System.out.println(studentMax); System.out.println(studentMin); Student studentMax1 = list.stream().max((a, b) -> { if (a.getHign() > b.getHign()) { return 1; } else { return -1; } }).get(); Student studentMin1 = list.stream().min((a, b) -> { if (a.getHign() > b.getHign()) { return 1; } else { return -1; } }).get(); System.out.println(studentMax1); System.out.println(studentMin1); Student studentMax2 = list.stream().max(Comparator.comparing(Student::getHign)).get(); System.out.println(studentMax2);当然了,也可以用sort进行排序,对于double也可以使用上述策略// 年龄从低到高 list.sort((a, b) -> a.getAge() - b.getAge()); System.out.println(list);// 身高升序 list.sort(Comparator.comparing(Student::getHign)); System.out.println(list);// 身高降序 简而言之就是o2.getHign()-o1.getHign()>0,但是compare方法只返回int,强制类型转换会导致不精准 list.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (o1.getHign() < o2.getHign()) { return 1; } else { return -1; } } }); System.out.println(list);stream排序用sorted即可Stream<Student> asc = list.stream().sorted((a,b)->a.getAge()-b.getAge());asc = list.stream().sorted(Comparator.comparingInt(Student::getAge));Stream<Student> desc = list.stream().sorted((a,b)->b.getAge()-a.getAge());System.out.println(asc.collect(Collectors.toList()));System.out.println(desc.collect(Collectors.toList()));