Spring Boot @Scheduled不适用于数据库事务

时间:2017-12-26 18:25:54

标签: java spring-boot

我有一个预定的工作,它将删除数据库中的所有记录并每隔10分钟插入新数据。如果我通过创建一个Web服务手动调用服务,这很有效。但是,预定作业无法删除和插入。我正在使用JPA删除所有记录并保存。我也保留了@Transactional注释,但到目前为止还没有运气。有什么想法吗?

static String super_reduced_string(String s){
    for (int i = 0; i < s.length()-1; i++) {
        if (s.charAt(i) == s.charAt(i+1)) {
            s = s.substring(0, i) + s.substring(i+2);
            i = -1; // so after the ++ at the end of the loop, the next loop-run will have i==0.
        }
    }
    if (s.length() == 0) {
        return("Empty String");
    } else {
        return(s);
    }
}

我的MainService.java

@Service
public class ScheduledService {

    @Autowired
    MainService mainService;

    @Scheduled(fixedDelay=100000, initialDelay=10000)
    public void updateAllScreensScheduled() {
        mainService.updateAllScreens();
    }
}

2 个答案:

答案 0 :(得分:0)

最后我用这种方式解决了这个问题:

  1. 在Application类中添加了@EnableTransactionManagement并添加了 PlatformTransactionManager Bean。检查以下代码:
  2. @Autowired
    private EntityManagerFactory entityManagerFactory;
    
    @Bean
    public PlatformTransactionManager transactionManager()
    {
    return new JpaTransactionManager(entityManagerFactory);
    }
    

    这是导入:

    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    1. 在我的调度程序代码中添加了以下代码:
    2. @Scheduled(fixedRate = 60 *10*1000)
          @Transactional(propagation=Propagation.REQUIRES_NEW)
          public void reportCurrentTime() {
          doDatabaseTransaction();
          }
      
      Here is the imports :
      
      import org.springframework.scheduling.annotation.Scheduled;
      import org.springframework.stereotype.Controller;
      import org.springframework.transaction.annotation.Propagation;
      import org.springframework.transaction.annotation.Transactional;
      

      希望这能解决您的问题:)

答案 1 :(得分:0)

我通过创建一个以internal/modules/cjs/loader.js:584 throw err; ^ Error: Cannot find module '/app/server/server.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15) at Function.Module._load (internal/modules/cjs/loader.js:508:25) at Function.Module.runMain (internal/modules/cjs/loader.js:754:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3) 为主体并@Async进行注释的方法mainService.updateAllScreens();来解决了这个问题

所以updateAllScreens()看起来就像是异步方法的调用

P.S。不要忘记将updateAllScreensScheduled()添加到配置中