Created
July 5, 2020 08:02
-
-
Save nitinbhojwani/c077f5c4e1ebba103a68b142b53f46e5 to your computer and use it in GitHub Desktop.
Test Scheduler using Kotlin and SpringFramework - tested for Target JVM 1.8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.org.schedules | |
import com.example.org.services.ConstructorInjection | |
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty | |
import org.springframework.scheduling.annotation.EnableScheduling | |
import org.springframework.scheduling.annotation.Scheduled | |
import org.springframework.stereotype.Component | |
/** | |
* TestScheduler to schedule a method to run with fixedDelay | |
* The class should be open for EnableScheduling to work | |
*/ | |
@Component | |
@ConditionalOnProperty("schedules.test-scheduler.enabled") // optional | |
@EnableScheduling | |
open class TestScheduler(private val constructorInjection: ConstructorInjection) { | |
/** | |
* The function should be open for the Scheduling to work correctly | |
* NOTE: This won't throw an error/exception otherwise | |
* It's just the constructorInjection would be null if used inside this function | |
* and one would waste lot of time finding why | |
*/ | |
@Scheduled(fixedDelay = DELAY_IN_MS) | |
open fun runWithDelay() { | |
constructorInjection.someMethod() | |
} | |
companion object { | |
// fixedDelay of 30 secs - Provide delay as a constant in companion object can directly hardcode too | |
const val DELAY_IN_MS = 30000L | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment