springBoot下java代码mysql数据库定时任务(创建表)

3 篇文章 0 订阅
3 篇文章 0 订阅

springBoot下用java代码创建表

  1. 首先找到application.yml配置文件进行数据库连接配置
    在这里插入图片描述2…编写初始化数据库表类
    这里就先写个demo用作测试
    在项目目下新建一个包,报名任意,在包下新建一个类,类名称为”CreateTableTest.java"(类名称也可以自己命名)。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Repository
@PropertySource({"classpath:application.yml"})
public class CreateTableTest {

    @Value(value = "com.mysql.jdbc.Driver")
    private String driver;
    @Value(value = "${custom.datasource.gateway.url}")
    private String url;

    @Value(value = "${custom.datasource.gateway.username}")
    private String userName;

    @Value(value = "${custom.datasource.gateway.password}")
    private String password;

    @PostConstruct
    public void init() throws SQLException, ClassNotFoundException{
        System.out.println("开始执行新建数据库了"+url+"  "+userName+"  "+password);
        //连接数据库
        Class.forName(driver);
        //测试url中是否包含useSSL字段,没有则添加设该字段且禁用
        if( url.indexOf("?") == -1 ){
            url = url + "?useSSL=false" ;
        }
        else if( url.indexOf("useSSL=false") == -1 || url.indexOf("useSSL=true") == -1 )
        {
            url = url + "&useSSL=false";
        }
        Connection conn = DriverManager.getConnection(url, userName, password);
        Statement stat = conn.createStatement();
        //获取数据库表名
       
        ResultSet rs = conn.getMetaData().getTables(null, null, "test_sche", null);
        // 判断表是否存在,如果存在则什么都不做,否则创建表
        if( rs.next() ){
            System.out.println("数据库已存在");
            return;
        }
        else{
            stat.executeUpdate("CREATE TABLE test_sche("
            +"`id` int(11) NOT NULL,"
            +"`counts` int(11) DEFAULT NULL,"
            +"PRIMARY KEY (`id`)"
            +") ENGINE=InnoDB DEFAULT CHARSET=utf8"
            );
          
        }
        // 释放资源
        stat.close();
        conn.close();
    }
}

3.运行查看结果
找到项目中的Application.java类,运行该类,等运行完毕后再打开sqlyog查看自己的数据库,发现数据库中已经创建好了一个表为"test_ache"的表和表中的相关字段。
在这里插入图片描述

用定时任务创建表(一分钟创建一个)

刚刚演示了最基本的java代码创建表,现在进阶一下写个定时任务创建表这里要用到
@Scheduled这个注解
1.在Application.java加上@EnableScheduling注解
在这里插入图片描述
2.编写新的创建表代码这里用的test_+时+分做表名

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Repository
public class CreateTableTest {

   @Value(value = "com.mysql.jdbc.Driver")
    private String driver;
    @Value(value = "${custom.datasource.gateway.url}")
    private String url;

    @Value(value = "${custom.datasource.gateway.username}")
    private String userName;

    @Value(value = "${custom.datasource.gateway.password}")
    private String password;
    @Scheduled(cron = "0 */1 * * * ?")
    //@PostConstruct
    public void init() throws SQLException, ClassNotFoundException{
        Calendar now = Calendar.getInstance();
        System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
        System.out.println("分: " + now.get(Calendar.MINUTE));
        System.out.println("开始执行新建数据库了"+url+"  "+userName+"  "+password);
        //连接数据库
        Class.forName(driver);
        //测试url中是否包含useSSL字段,没有则添加设该字段且禁用
        if( url.indexOf("?") == -1 ){
            url = url + "?useSSL=false" ;
        }
        else if( url.indexOf("useSSL=false") == -1 || url.indexOf("useSSL=true") == -1 )
        {
            url = url + "&useSSL=false";
        }
        Connection conn = DriverManager.getConnection(url, userName, password);
        Statement stat = conn.createStatement();
        //获取数据库表名
        String tableName ="test_"+now.get(Calendar.HOUR_OF_DAY)+now.get(Calendar.MINUTE);
      
        ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null);
        // 判断表是否存在,如果存在则什么都不做,否则创建表
        if( rs.next() ){
            System.out.println("数据库已存在");
            return;
        }
        else{
            
            //创建行政区划表
            // String table2 ="test"+now.get(Calendar.YEAR)+""+(now.get(Calendar.MONTH) + 1)+""+now.get(Calendar.DAY_OF_MONTH);
            String test = "CREATE TABLE "+tableName+" (";
            stat.executeUpdate(test
            +"`id` int(11) NOT NULL,"
            +"`counts` int(11) DEFAULT NULL,"
            +"PRIMARY KEY (`id`)"
            +") ENGINE=InnoDB DEFAULT CHARSET=utf8"

            );
            System.out.println("成功创建"+tableName);

        }
        // 释放资源
        stat.close();
        conn.close();
    }
}

3.找到项目中的Application.java类,运行该类,等运行完毕后再打开sqlyog查看自己的数据库每隔一分钟会看到新表创建成功
在这里插入图片描述可以看到每一分钟创建一个表成功了

注解及作用

  1. @Scheduled
  2. @PostConstruct
  3. 每天凌晨2点 0 0 2 * * ?和每天隔一小时 0 * */1 * * ?

例1:每隔5秒执行一次:*/5 * * * * ?

例2:每隔5分执行一次:0 */5 * * * ?

在26分、29分、33分执行一次:0 26,29,33 * * * ?

例3:每天半夜12点30分执行一次:0 30 0 * * ? (注意日期域为0不是24)

每天凌晨1点执行一次:0 0 1 * * ?

每天上午10:15执行一次: 0 15 10 ? * * 或 0 15 10 * * ? 或 0 15 10 * * ? *

每天中午十二点执行一次:0 0 12 * * ?

每天14点到14:59分,每1分钟执行一次:0 * 14 * * ?

每天14点到14:05分,每1分钟执行一次:0 0-5 14 * * ?

每天14点到14:55分,每5分钟执行一次:0 0/5 14 * * ?

每天14点到14:55分,和18点到18点55分,每5分钟执行一次:0 0/5 14,18 * * ?

每天18点执行一次:0 0 18 * * ?

每天18点、22点执行一次:0 0 18,22 * * ?

每天7点到23点,每整点执行一次:0 0 7-23 * * ?

每个整点执行一次:0 0 0/1 * * ?

每天凌晨2点 0 0 2 * * ?和每天隔一小时 0 * */1 * * ?

例1:每隔5秒执行一次:*/5 * * * * ?

例2:每隔5分执行一次:0 */5 * * * ?

在26分、29分、33分执行一次:0 26,29,33 * * * ?

例3:每天半夜12点30分执行一次:0 30 0 * * ? (注意日期域为0不是24)

每天凌晨1点执行一次:0 0 1 * * ?

每天上午10:15执行一次: 0 15 10 ? * * 或 0 15 10 * * ? 或 0 15 10 * * ? *

每天中午十二点执行一次:0 0 12 * * ?

每天14点到14:59分,每1分钟执行一次:0 * 14 * * ?

每天14点到14:05分,每1分钟执行一次:0 0-5 14 * * ?

每天14点到14:55分,每5分钟执行一次:0 0/5 14 * * ?

每天14点到14:55分,和18点到18点55分,每5分钟执行一次:0 0/5 14,18 * * ?

每天18点执行一次:0 0 18 * * ?

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以通过集成Quartz框架来实现动态创建定时任务。下面是一个简单的示例,演示如何查询数据库创建定时任务。 首先,需要在pom.xml文件中添加Quartz和MySQL的依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> ``` 然后,需要在application.properties文件中配置数据库连接信息: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 接下来,可以定义一个ScheduledJob实体类,用于映射数据库中的定时任务数据: ```java @Entity @Table(name = "scheduled_job") public class ScheduledJob { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String group; private String cronExpression; private String description; // getters and setters } ``` 然后,创建一个JobFactory类,继承SpringBeanJobFactory,并重写createJobInstance方法,用于将Job实例交给Spring容器进行管理: ```java public class JobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(final ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; } } ``` 最后,创建一个JobScheduler类,用于从数据库中读取定时任务数据,并创建对应的定时任务: ```java @Component public class JobScheduler { @Autowired private SchedulerFactory schedulerFactory; @Autowired private JobFactory jobFactory; @Autowired private DataSource dataSource; @PostConstruct public void init() throws Exception { final Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.setJobFactory(jobFactory); final String sql = "select * from scheduled_job"; try (final Connection connection = dataSource.getConnection(); final PreparedStatement statement = connection.prepareStatement(sql); final ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { final JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class) .withIdentity(resultSet.getString("name"), resultSet.getString("group")) .withDescription(resultSet.getString("description")) .build(); final Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(resultSet.getString("name"), resultSet.getString("group")) .withSchedule(CronScheduleBuilder.cronSchedule(resultSet.getString("cron_expression"))) .build(); scheduler.scheduleJob(jobDetail, trigger); } scheduler.start(); } } } ``` 在上面的代码中,首先通过SchedulerFactory获取Scheduler实例,并设置JobFactory。然后,通过数据库查询语句从数据库中获取定时任务数据,并创建对应的JobDetail和Trigger实例。最后,将JobDetail和Trigger实例添加到Scheduler中,并启动Scheduler。 需要注意的是,QuartzJob类需要继承QuartzJobBean,并实现executeInternal方法,用于执行定时任务的具体逻辑: ```java public class QuartzJob extends QuartzJobBean { @Override protected void executeInternal(final JobExecutionContext context) throws JobExecutionException { // 定时任务逻辑 } } ``` 至此,一个动态创建定时任务的示例就完成了。需要注意的是,该示例仅供参考,实际应用中还需要考虑很多细节问题,如异常处理、任务状态管理等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值