SpringScheduling etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
SpringScheduling etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

29 Eylül 2023 Cuma

SpringScheduling Shedlock JdbcTemplateLockProvider Sınıfı

Giriş
Şu satırı dahil ederiz
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
constructor
JdbcTemplateLockProvider.Configuration .builder()...build() şeklinde kullanılır


JdbcTemplateLockProvider.Configuration.Builder Sınıfı
Bu sınıf hemen hemen her yerde aynı şekilde kullanılıyor

withJdbcTemplate metodu
Örnek
Şöyle yaparız
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;

@Configuration
public class ShedLockConfig {

  @Bean
  public LockProvider lockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration
      .builder()
      .withJdbcTemplate(new JdbcTemplate(dataSource))
      .usingDbTime() // Use database time for locks
      .build());
  }
}
Örnek
Şöyle yaparız
@Bean
@SuppressWarnings("unused")
public LockProvider lockProvider(DataSource dataSource) {
  return new JdbcTemplateLockProvider(
    JdbcTemplateLockProvider.Configuration.builder()
      .withJdbcTemplate(new JdbcTemplate(datasource))
      .usingDbTime ()
      .build ()
  );
}
Örnek
Şöyle yaparız
@Bean
public LockProvider lockProvider(DataSource dataSource) {  
  return new JdbcTemplateLockProvider(  
    JdbcTemplateLockProvider.Configuration.builder()  
      .withJdbcTemplate(new JdbcTemplate(dataSource))  
      .usingDbTime() // Works on Postgres, MySQL, MariaDb, MS SQL, Oracle, DB2, HSQL, H2  
      .build()  
  );  
}

12 Haziran 2023 Pazartesi

SpringScheduling @Scheduled Anotasyonu fixedRate Alanı

Giriş
milisaniye cinsindendir. Açıklaması şöyle. İlk çalışma başladıktan sonra fixedRate kadar bekledikten sonra ikinci çalışma başlar.
method can be scheduled to run with a fixed interval using fixedRate parameter.
Örnek
Şöyle yaparız.
@Scheduled(fixedRate = 5000)
Örnek
Şöyle yaparız.
@Scheduled(initialDelay=60*1000, fixedRate=60*1000) //60secs
private void method() {
  ...  
}
Örnek
String olarak vermek için şöyle yaparız.
@Scheduled(initialDelayString = "1000", fixedDelayString = "1000")
Eğer İş Zamanında Bitmezse Ne Olur ?
Thread pool kullansak bile birinci iş zamanında bitmezse ikinci iş ile örtüşecek şekilde başlamaz


8 Haziran 2023 Perşembe

SpringScheduling Shedlock From Configuration

Giriş
Açıklaması şöyle
Locking without a framework
It is possible to use ShedLock without a framework
Şöyle yaparız. Burada LockingTaskExecutor belirtilen Runnable nesnesini belirtilen lock ismi ile birlikte çalıştırır.
LockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider);
... Instant lockAtMostUntil = Instant.now().plusSeconds(600); executor.executeWithLock(runnable, new LockConfiguration("lockName", lockAtMostUntil));
Örnek
Şöyle yaparız. Bu örnekte Spring kodları dolaşılıyor ve her Cron işi LockingTaskExecutor ile sarmalanıyor
import org.springframework.scheduling.annotation.SchedulingConfigurer
import org.springframework.scheduling.config.CronTask import org.springframework.scheduling.config.ScheduledTaskRegistrar; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockingTaskExecutor; @Configuration @RequiredArgsConstructor public class SchedulerConfig implements SchedulingConfigurer { private final LockingTaskExecutor lockingTaskExecutor; private final TaskProperties taskProperties; private final Map<String, ScheduledTask> scheduledTaskMap = new HashMap<>(); private ScheduledTaskRegistrar taskRegistrar; public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { this.taskRegistrar = taskRegistrar; taskRegistrar.setScheduler(taskExecutor()); taskProperties.getTasks().forEach(this::addTask); } public void addTask(TaskProperty taskProperty) { Runnable task = () -> log.info("Running task with name {}", taskProperty.getName()); ScheduledTask scheduledTask = taskRegistrar.scheduleCronTask( new CronTask(() -> lockingTaskExecutor.executeWithLock(task, new LockConfiguration(Instant.now(), taskProperty.getName(), taskProperty.getLockAtMostFor(), taskProperty.getLockAtLeastFor())) , taskProperty.getCron())); scheduledTaskMap.put(taskProperty.getName(), scheduledTask); } }


27 Ocak 2023 Cuma

SpringScheduling @Scheduled Anotasyonu Unit Test

Örnek
Kod şöyle olsun
@Component
public class MyScheduler {

    private final MyService myService;

    @Scheduled(fixedDelayString = "${app.scheduler.delay-ms}")
    public void run() {
        myService.call();
    }
}
Şöyle yaparız
@ExtendWith(SpringExtension.class)
@SpringBootTest( classes = { MyApplication.class, MySchedulerIntegrationTest.MySchedulerTestConfig.class }, properties = { "app.scheduler.delay-ms=200" }) @ActiveProfiles("local") class MySchedulerIntegrationTest { // Dependency injected into scheduler, we mock it to verify is being called. @MockBean private MyService myService; @Test void shouldStartScheduler() { await().atMost(300, TimeUnit.MILLISECONDS) .untilAsserted(() -> { verify(myService, times(2)).call(); }); } @Configuration static class MySchedulerTestConfig { // If you need to mock anything in your context, add here using @MockBean. } }


19 Temmuz 2021 Pazartesi

SpringScheduling Shedlock Kullanımı

Giriş
Açıklaması şöyle. ShedLock kütüphanesi, distributed lock için veri tabanını kullanıyor.
ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread). Please note, that if one task is already being executed on one node, execution on other nodes does not wait, it is simply skipped.
Açıklaması şöyle. 
The high level idea of ShedLock is pretty simple. When a given instance is executing a scheduler method of your application, a data source update call will happen with the provided configuration. The configuration will contain a unique name for the scheduler and also it contains 3 other columns lock_until, locked_at, and locked_by. If another instance tries to run the same scheduler method, the first step is to check if it is locked, in case it is locked, then it will not be executed.
Maven
Shedlock 3 kısımdan oluşuyor
1. Core
2. Integration 
3. Lock Provider
Integration ile Core bağımlılığı da geliyor. Lock Provider bağımlılığı ile de arkada kullanılacak veri tabanı seçiliyor.

Örnek - Spring
Şu satırı dahil ederiz. Lock provider olarak kullanılacak kütüphaneyi de dahil etmek gerekiyor. Burada Lock provider olarak JDBC kullanılıyor.
<dependency>
  <groupdId>net.javacrumbs.shedlock</groupdId>
  <artifactId>shedlock-spring</artifactId>
  <version>4.23.0</version>
</dependency>
<dependency>
  <groupdId>net.javacrumbs.shedlock</groupdId>
  <artifactId>shedlock-provider-jdbc-template</artifactId>
  <version>4.23.0</version>
</dependency>
Gradle
Şu satırı dahil ederiz
implementation 'net.javacrumbs.shedlock:shedlock-spring:5.3.0'
implementation 'net.javacrumbs.shedlock:shedlock-provider-jdbc-template:5.3.0'
Daha sonra bir tablo oluştururuz
CREATE TABLE shedlock(name VARCHAR(64) NOT NULL, lock_until TIMESTAMP(3) NOT NULL,
  locked_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
locked_by VARCHAR(255) NOT NULL, PRIMARY KEY (name));
Kullanım
1. Spring'e ait @EnableScheduling anotasyonunun olduğu koda ilave olarak @EnableSchedulerLock anotasyonu tanımlanır. Burada varsayılan ayarlar belirtiliyor
Yani şöyle yaparız
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
class MySpringConfiguration {
    ...
}
2. Bir LockProvider tanımlanır. Açıklaması şöyle
You’ll need to create a LockProvider bean and specify which lock providers to use (e.g., database-backed locks, ZooKeeper, Redis, etc.).
Lock provider olarak bir sürü farklı şey kullanılabiliyor. Liste burada. 
JdbcTemplateLockProvider yazısına bakabilirsiniz

3. Spring'e ait @Scheduled anotasyonunun olduğu koda anotasyon olarak @SchedulerLock Anotasyonu ilave edilir. Yani şöyle yaparız
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;

...

@Scheduled(...)
@SchedulerLock(name = "scheduledTaskName")
public void scheduledTask() {
    // To assert that the lock is held (prevents misconfiguration errors)
    LockAssert.assertLocked();
    // do something
}
@EnableSchedulerLock Anotasyonu
Açıklaması şöyle
We need to enable Shedlock with a default lock for a maximum of 5 minutes.
...
Thus, during the next tick of the scheduler, each instance will try to write a line about itself in the lock table, and the first one who succeeds will continue executing the task. Everyone else will skip the tick.

Lock on the task will hang in our case for a maximum of 5 minutes. Upon completion of the task, the instance will remove the lock in the table. If 5 minutes have passed and the lock has not been removed, other instances will consider that that instance has frozen while the task is being executed.
defaultLockAtLeastFor Alanı
Örnek
Şöyle yaparız
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor="PT20s",defaultLockAtLeastFor="PT5s")
public class SchedulerConfiguration {

  @Bean
  public LockProvider lockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(
      JdbcTemplateLockProvider.Configuration.builder()
        .withJdbcTemplate(new JdbcTemplate(dataSource))
        .build()
    );
  }
}
defaultLockAtMostFor Alanı
Örnek
Şöyle yaparız
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "5m")
public class ApplicationConfiguration {
}
Örnek
Şöyle yaparız
@EnableSchedulerLock(defualtLockAtMostFor = "PT45S",defaultLockAtLeastFor = "PT45S")
@Configuration
public class SchedulerLockConfig {
  ...
}

21 Ocak 2021 Perşembe

SpringScheduling SchedulingConfigurer Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.scheduling.annotation.SchedulingConfigurer;
SpringScheduling kullanırken daha fazla kontrol istersek bu sınıfı kullanmak gerekir. Açıklaması şöyle.
When more control is desired, a @Configuration class may implement SchedulingConfigurer. This allows access to the underlying ScheduledTaskRegistrar instance.
configureTasks metodu
ScheduledTaskRegistrar sınıfı yazısına bakabilirsiniz.

Örnek
Şöyle yaparız. Burada SpringScheduling tarafından kullanılacak yeni bir thread pool tanımlanıyor
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Configuration
public class SchedulerConfiguration implements SchedulingConfigurer {

  @Bean
  public Executor taskExecutor() {
    return Executors.newScheduledThreadPool(100);
  }

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(taskExecutor());
  }
}
Aslında Spring kapanırken thread pool da düzgün kapansın istiyorsak destroyMethod belirterek şöyle yaparız
@Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
   return Executors.newScheduledThreadPool(1);
}

SpringScheduling Kullanımı

Giriş
1. 1. @EnableScheduling anotasyonu koda eklenir.
2. Bean sınıfının bir metodu @Scheduled anotasyonu ile işaretlenir. Ancak bu genellikle yeterli olmaz. 

Çünkü 
2.1. SpringScheduling thread pool büyüklüğü 1 tek thread ile sınırlandırılmıştır. Yani thread pool büyüklüğü yetersizdir. Bu thread'in ismi "scheduling-1" dir.

Bu yüzden SchedulingConfigurer ile yeni bir thread pool yaratılır. Açıklaması şöyle
By default, Spring @Scheduled annotation uses default thread pool of size 1 ...
Bu ayarı yapınca yeni thread'lerin ismi "pool-X-thread-Y" haline gelir.

2.2. Thread pool büyüklüğü artırılsa bile aynı @Scheduled metodları sırayla çalıştırılır. Bu yüzden @Scheduled metodlarını @Async ile işaretlemek gerekebilir. Açıklaması şöyle
executions of scheduled method happen synchronously in respect to other executions of method.
Örnek
Şöyle yaparız
@Component
public class ScheduledService {

  @Scheduled(fixedDelay = 1000)
  @Async
  public void run1(){
    ...
  }
}
2.3 Aynı bean iki defa yüklenirse kod iki defa tetiklenebilir. Açıklaması şöyle. Bean'in bir defa yüklenmiş olmasına dikkat edilmeli.
Make sure that you are not initializing multiple instances of the same @Scheduled annotation class at runtime, unless you do want to schedule callbacks to each such instance. Related to this, make sure that you do not use @Configurable on bean classes which are annotated with @Scheduled and registered as regular Spring beans with the container: You would get double initialization otherwise, once through the container and once through the @Configurable aspect, with the consequence of each @Scheduled method being invoked twice.
Bean Olarak ScheduledTask Tanımlama 
Sınıf @Component veya @Service olarak işaretli olmalıdır. Şöyle yaparız.
@Component 
public class ScheduledTask {

  @Scheduled(fixedRate = 60*1000)
  public void run() {
    ...
  }
}
XML Olarak ScheduledTask Tanımlama
Örnek - Dakika
XML ile tanımlamak için şöyle yaparız. Burada bean ve metod ismini belirtiriz.
<task:scheduled-tasks>
  <task:scheduled ref="offerScheduler" method="processOffer" cron="0 1 * * * *" />
</task:scheduled-tasks>
Bean'i tanımlamak için şöyle yaparız.
@Component
public class OfferScheduler {

  public void processOffer(){
    ...
  }
}
Örnek - Saat
Şöyle yaparız. Her gün sabah saat 3'te.
<task:scheduled ref="jobService" method="jobToRun" cron="0 0 3 * * *" />
Örnek
Şöyle yaparız.
<task:scheduled-tasks scheduler="myScheduler">
  <task:scheduled ref="restBean" method="addPhoto" fixed-delay="5000"/>
</task:scheduled-tasks>

<task:scheduler id="myScheduler"/>
Dağıtık Ortamda Scheduling
3 tane çözüm var. Açıklaması şöyle
1. You can configure your application to have multiple profiles. For example, use another profile ‘cron’. And start your application on only one server with this profile. So for example, in a production environment, you have three servers (S1, S2, S3), then you could run on S1 with profile prod and cron(-Dspring.profiles.active=prod,cron). And on S2 and S3 just use prod profile(-Dspring.profiles.active=prod). And in code, you can use @Profile("cron") scheduler classes. This way it will be executed only when the cron profile is active.

2. Use a distributed lock. If you have Zookeeper in your environment, you can use this to achieve a distributed locking system.

3. You can use some database(mysql) and create a sample code to get a lock on one of the tables and add an entry. And whichever instance gets the lock, will make an entry in this database and will execute the cron job. You need to put a check in your code if getLock() is successful. only then proceed with execution. Mysql has utilities like LOCK TABLES, which you could use to get away with concurrent read/writes.
ShedLock kütüphanesi, distributed lock için veri tabanını kullanıyor. Yani 3. çözüm

ShedLock Kullanımı
Shedlock yazısına taşıdım



6 Nisan 2020 Pazartesi

SpringScheduling AsyncResult Sınıfı - Kullanmayın

Giriş
Şu satırı dahil ederiz.
import org.springframework.scheduling.annotation.AsyncResult;
org.springframework.scheduling.annotation.AsyncResult sınıfı Future ve  ListenableFuture arayüzülerini gerçekleştirir. Bence CompletableFuture sınıfı varken artık bu sınıfı kullanmaya gerek yok.

constructor
Örnek
Şöyle yaparız
@Service
public class AsyncService {

  @Async
  public Future<String> asyncInvokeReturnFuture(int i) {
    Future<String> future;
    try {
      Thread.sleep(1000 * 1);
      future = new AsyncResult<String>("success:" + i);
    } catch (InterruptedException e) {
      future = new AsyncResult<String>("error");
    }
    return future;
  }
}
Örnek
 Şöyle yaparız.
@Async
@Override
public Future<Response> doTasks(Student student) {
  Response response = new Response();
  //do Tasks
  return new AsyncResult<Response>(response);
}
Örnek
Şöyle yaparız.
@Service
@Scope("prototype")
public class PostMan2 implements PostMans2 {

 
  @Async
  public Future<String> deliverLetter(String message, int i) {
    ...
    String res = "result!";
    return new AsyncResult<String>(res);
  }
  ...
}

completable metodu
Şöyle yaparız.
@Service
public class Aservice {

  @Async
  public CompletableFuture<Integer> getData() throws InterruptedException {
    Thread.sleep(1000 * 3); // sleep for 3 sec
    return new AsyncResult<>(2).completable(); // wrap integer 2
  }
}