├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── kotlin │ └── com │ │ └── example │ │ └── demo │ │ ├── DemoApplication.kt │ │ ├── ScheduledJob.kt │ │ └── tracking │ │ ├── ScheduledJobController.kt │ │ ├── ScheduledJobRun.kt │ │ ├── ScheduledJobTracker.kt │ │ ├── ScheduledJobTrackingAspect.kt │ │ └── TrackedScheduledJob.kt └── resources │ └── application.yml └── test └── kotlin └── com └── example └── demo └── DemoApplicationTests.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | /out/ 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /build/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | src/main/kotlin/com/example/demo/.DS_Store 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Kevin Grüneberg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # General 2 | 3 | This project demonstrates the tracking of scheduled jobs using Spring AOP. 4 | 5 | The tracking is fairly simple. The `ScheduledJobTrackingAspect` invokes every method with an `Scheduled` annotation and writes the start and end of the method into the `ScheduledJobTracker`. 6 | A UUID is assigned to the job upon start, since a single job can run multiple times at once. 7 | 8 | The data is available via `ScheduledJobController`. 9 | 10 | This is just a project demonstrating the tracking. I am considering to build a library that can be included in any spring boot project to enable tracking of scheduled tasks. 11 | 12 | ## Sample scheduled job 13 | 14 | The demo has a very simple scheduled job, that prints *foo* every 5 seconds. 15 | 16 | ```kotlin 17 | package com.example.demo 18 | 19 | import org.springframework.scheduling.annotation.Scheduled 20 | import org.springframework.stereotype.Component 21 | 22 | @Component 23 | class ScheduledJob { 24 | 25 | @Scheduled(fixedRate = 5000) 26 | fun println() = println("foo") 27 | 28 | } 29 | ``` 30 | 31 | ## Access data via REST 32 | 33 | `GET /scheduled-jobs/` 34 | 35 | ```json 36 | [ 37 | { 38 | "className": "com.example.demo.ScheduledJob", 39 | "methodName": "println", 40 | "fixedRate": 5000, 41 | "runs": [ 42 | { 43 | "uuid": "c5ca5c73-f1f6-4ced-a911-de0e43a78d78", 44 | "startedAt": "2018-05-15T23:38:11.177Z", 45 | "endedAt": "2018-05-15T23:38:11.182Z", 46 | "exception": null, 47 | "duration": "PT0.005S" 48 | }, 49 | { 50 | "uuid": "2dd54fc3-8753-41c1-91d2-a7ec33fda0e8", 51 | "startedAt": "2018-05-15T23:38:16.169Z", 52 | "endedAt": "2018-05-15T23:38:16.169Z", 53 | "exception": null, 54 | "duration": "PT0S" 55 | }, 56 | { 57 | "uuid": "6be5d3ad-924e-4aa6-aef8-a4b837b3e67f", 58 | "startedAt": "2018-05-15T23:38:21.170Z", 59 | "endedAt": "2018-05-15T23:38:21.170Z", 60 | "exception": null, 61 | "duration": "PT0S" 62 | }, 63 | { 64 | "uuid": "72dc2d85-d2f1-4875-9381-3d26f6c6512c", 65 | "startedAt": "2018-05-15T23:38:26.169Z", 66 | "endedAt": "2018-05-15T23:38:26.169Z", 67 | "exception": null, 68 | "duration": "PT0S" 69 | }, 70 | { 71 | "uuid": "e4f635ee-625b-4618-84ee-0cb0c2aa210e", 72 | "startedAt": "2018-05-15T23:38:31.169Z", 73 | "endedAt": "2018-05-15T23:38:31.169Z", 74 | "exception": null, 75 | "duration": "PT0S" 76 | } 77 | ], 78 | "status": "Idle", 79 | "averageDurationInMs": 1, 80 | "lastDurationInMs": 0, 81 | "lastRunStarted": "2018-05-15T23:38:31.169Z", 82 | "lastRunEnded": "2018-05-15T23:38:31.169Z" 83 | } 84 | ] 85 | ``` -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | kotlinVersion = '1.2.60' 4 | springBootVersion = '2.0.4.RELEASE' 5 | } 6 | repositories { 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" 11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 12 | } 13 | } 14 | 15 | apply plugin: 'kotlin' 16 | apply plugin: 'org.springframework.boot' 17 | apply plugin: 'io.spring.dependency-management' 18 | 19 | group = 'com.example' 20 | version = '0.0.1-SNAPSHOT' 21 | sourceCompatibility = 1.8 22 | 23 | compileKotlin { 24 | kotlinOptions { 25 | jvmTarget = "1.8" 26 | } 27 | } 28 | compileTestKotlin { 29 | kotlinOptions { 30 | jvmTarget = "1.8" 31 | } 32 | } 33 | 34 | repositories { 35 | mavenCentral() 36 | } 37 | 38 | dependencies { 39 | compile "org.springframework.boot:spring-boot-starter:$springBootVersion" 40 | compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion" 41 | compile "org.springframework.boot:spring-boot-starter-aop:$springBootVersion" 42 | 43 | compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" 44 | compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" 45 | testCompile "org.springframework.boot:spring-boot-starter-test:$springBootVersion" 46 | } 47 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevcodez/spring-boot-track-scheduled-tasks/14b06ab708f0941da84db12980aa49df296b196f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'demo' 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | import org.springframework.scheduling.annotation.EnableScheduling 6 | 7 | @SpringBootApplication 8 | @EnableScheduling 9 | class DemoApplication 10 | 11 | fun main(args: Array) { 12 | runApplication(*args) 13 | } 14 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/ScheduledJob.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.scheduling.annotation.Scheduled 4 | import org.springframework.stereotype.Component 5 | import java.util.* 6 | 7 | @Component 8 | open class ScheduledJob { 9 | 10 | @Scheduled(fixedRate = 5000) 11 | open fun println() = println("foo") 12 | 13 | @Scheduled(fixedRate = 15000) 14 | open fun regularJob() = println("Just a regular job") 15 | 16 | @Scheduled(fixedRate = 30000) 17 | open fun longRunningJob() { 18 | Thread.sleep(10000) 19 | } 20 | 21 | @Scheduled(fixedRate = 10000) 22 | open fun sometimesThrowingException() { 23 | val random = Random().nextInt(10) 24 | if (random <= 2) 25 | throw IllegalArgumentException("Random exception") 26 | } 27 | 28 | @Scheduled(fixedRate = 60000) 29 | open fun alwaysException() { 30 | throw IllegalArgumentException("Computer says no") 31 | } 32 | 33 | @Scheduled(initialDelay = 1000000000, fixedRate = 1000000000000000) 34 | open fun neverRunningJob() = println("never") 35 | 36 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/tracking/ScheduledJobController.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.tracking 2 | 3 | import org.springframework.beans.factory.annotation.Autowired 4 | import org.springframework.http.HttpStatus 5 | import org.springframework.http.ResponseEntity 6 | import org.springframework.stereotype.Controller 7 | import org.springframework.web.bind.annotation.CrossOrigin 8 | import org.springframework.web.bind.annotation.PathVariable 9 | import org.springframework.web.bind.annotation.RequestMapping 10 | import org.springframework.web.bind.annotation.RequestMethod 11 | 12 | @Controller 13 | @RequestMapping("\${tracking.scheduledJobs.path:/scheduled-jobs}") 14 | @CrossOrigin(origins = ["*"]) 15 | class ScheduledJobController @Autowired constructor( 16 | private val scheduledJobTracker: ScheduledJobTracker 17 | ) { 18 | 19 | @RequestMapping(method = [RequestMethod.GET]) 20 | fun getScheduledJobs(): ResponseEntity { 21 | val scheduledJobs = scheduledJobTracker.trackedJobs 22 | return ResponseEntity.ok(scheduledJobs) 23 | } 24 | 25 | @RequestMapping(value = ["{className}"], method = [RequestMethod.GET]) 26 | fun getScheduledJobsPerClass(@PathVariable(name = "className") className: String): ResponseEntity { 27 | val scheduledJobs = scheduledJobTracker.findJobsByClass(className) 28 | return ResponseEntity.ok(scheduledJobs) 29 | } 30 | 31 | @RequestMapping(value = ["{className}/{methodName}"], method = [RequestMethod.GET]) 32 | fun getScheduledJob( 33 | @PathVariable(name = "className") className: String, 34 | @PathVariable(name = "methodName") methodName: String 35 | ): ResponseEntity { 36 | val scheduledJob = scheduledJobTracker.findJobByClassAndMethod(className, methodName) 37 | if (scheduledJob == null) 38 | return ResponseEntity(HttpStatus.NOT_FOUND) 39 | 40 | return ResponseEntity.ok(scheduledJob) 41 | } 42 | 43 | @RequestMapping(value = ["{className}/{methodName}/{uuid}"], method = [RequestMethod.GET]) 44 | fun getScheduledJobRun( 45 | @PathVariable(name = "className") className: String, 46 | @PathVariable(name = "methodName") methodName: String, 47 | @PathVariable(name = "uuid") uuid: String 48 | ): ResponseEntity { 49 | val scheduledJobRun = scheduledJobTracker.findRunByUuid(className, methodName, uuid) 50 | if (scheduledJobRun == null) 51 | return ResponseEntity(HttpStatus.NOT_FOUND) 52 | 53 | return ResponseEntity.ok(scheduledJobRun) 54 | } 55 | 56 | @RequestMapping( 57 | value = ["{className}/{methodName}"], 58 | method = [RequestMethod.POST] 59 | ) 60 | open fun triggerJob( 61 | @PathVariable(name = "className") className: String, 62 | @PathVariable(name = "methodName") methodName: String 63 | ): ResponseEntity { 64 | val successful = scheduledJobTracker.triggerJob(className, methodName) 65 | 66 | if (successful) 67 | return ResponseEntity(HttpStatus.OK) 68 | else 69 | return ResponseEntity(HttpStatus.BAD_REQUEST) 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/tracking/ScheduledJobRun.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.tracking 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude 4 | import com.fasterxml.jackson.annotation.JsonProperty 5 | import java.time.Duration 6 | import java.time.Instant 7 | import java.util.* 8 | 9 | @JsonInclude(value = JsonInclude.Include.NON_NULL) 10 | data class ScheduledJobRun( 11 | val uuid: UUID, 12 | val startedAt: Instant, 13 | val endedAt: Instant? = null, 14 | val exception: Throwable? = null 15 | ) { 16 | 17 | @JsonProperty 18 | fun duration(): Long? { 19 | if (endedAt == null) 20 | return null 21 | 22 | return Duration.between(startedAt, endedAt).toMillis() 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/tracking/ScheduledJobTracker.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.tracking 2 | 3 | import org.aspectj.lang.reflect.MethodSignature 4 | import org.springframework.beans.factory.annotation.Autowired 5 | import org.springframework.scheduling.annotation.Scheduled 6 | import org.springframework.scheduling.config.ScheduledTaskHolder 7 | import org.springframework.scheduling.support.ScheduledMethodRunnable 8 | import org.springframework.stereotype.Component 9 | import java.time.Instant 10 | import java.util.* 11 | import kotlin.collections.HashSet 12 | 13 | @Component 14 | class ScheduledJobTracker @Autowired constructor( 15 | private val scheduledTaskHolder: ScheduledTaskHolder 16 | ) { 17 | 18 | var trackedJobs: MutableSet = HashSet() 19 | 20 | init { 21 | initJobs() 22 | } 23 | 24 | private fun initJobs() { 25 | val scheduledTasks = scheduledTaskHolder.scheduledTasks 26 | scheduledTasks.forEach { 27 | val runnable = it.task.runnable as ScheduledMethodRunnable 28 | val annotation = runnable.method.getAnnotation( 29 | Scheduled::class.java 30 | ) 31 | 32 | trackedJobs.add( 33 | TrackedScheduledJob( 34 | className = runnable.method.declaringClass.name, 35 | methodName = runnable.method.name, 36 | settings = Settings( 37 | cron = nullIfEmptyString(annotation.cron), 38 | fixedRate = nullIfNegativeNumber(annotation.fixedRate), 39 | fixedRateString = nullIfEmptyString(annotation.fixedRateString), 40 | initialDelay = nullIfNegativeNumber(annotation.initialDelay), 41 | initialDelayString = nullIfEmptyString(annotation.initialDelayString), 42 | fixedDelay = nullIfNegativeNumber(annotation.fixedDelay), 43 | fixedDelayString = nullIfEmptyString(annotation.fixedDelayString) 44 | ) 45 | ) 46 | ) 47 | } 48 | } 49 | 50 | open fun triggerJob(className: String, methodName: String): Boolean { 51 | val job = findJobByClassAndMethod(className, methodName) 52 | if (job != null && job.latestRun()?.endedAt == null) 53 | return false 54 | 55 | val scheduledTasks = scheduledTaskHolder.scheduledTasks 56 | val matchingJob = scheduledTasks 57 | .map { it.task.runnable as ScheduledMethodRunnable } 58 | .firstOrNull { it.method.declaringClass.name == className && it.method.name == methodName } 59 | if (matchingJob != null) 60 | matchingJob.run() 61 | 62 | return matchingJob != null 63 | } 64 | 65 | fun jobStart(signature: MethodSignature): UUID { 66 | val uuid = UUID.randomUUID() 67 | 68 | val scheduledJob = get(signature) 69 | scheduledJob.addRun( 70 | ScheduledJobRun( 71 | uuid = uuid, 72 | startedAt = Instant.now() 73 | ) 74 | ) 75 | 76 | return uuid 77 | } 78 | 79 | private fun get(signature: MethodSignature): TrackedScheduledJob { 80 | val className = signature.declaringTypeName 81 | val methodName = signature.method.name 82 | 83 | return trackedJobs.find { it.className == className && it.methodName == methodName }!! 84 | } 85 | 86 | fun jobEnd(uuid: UUID, signature: MethodSignature, exception: Throwable?) { 87 | val className = signature.declaringTypeName 88 | val methodName = signature.method.name 89 | val trackedJob = trackedJobs.find { it.className == className && it.methodName == methodName }!! 90 | trackedJob.endRun(uuid, exception) 91 | } 92 | 93 | private fun nullIfEmptyString(str: String): String? { 94 | return if (str.isEmpty()) null else str 95 | } 96 | 97 | private fun nullIfNegativeNumber(number: Long): Long? { 98 | return if (number < 0) null else number 99 | } 100 | 101 | fun findJobsByClass(className: String): List { 102 | return trackedJobs.filter { it.className == className } 103 | } 104 | 105 | fun findJobByClassAndMethod(className: String, methodName: String): TrackedScheduledJob? { 106 | return trackedJobs.firstOrNull { it.className == className && it.methodName == methodName } 107 | } 108 | 109 | fun findRunByUuid(className: String, methodName: String, uuid: String): ScheduledJobRun? { 110 | val scheduledJob = findJobByClassAndMethod(className, methodName) 111 | if (scheduledJob == null) 112 | return null 113 | 114 | return scheduledJob.runs.firstOrNull { it.uuid.toString() == uuid } 115 | } 116 | } 117 | 118 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/tracking/ScheduledJobTrackingAspect.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.tracking 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint 4 | import org.aspectj.lang.annotation.Around 5 | import org.aspectj.lang.annotation.Aspect 6 | import org.aspectj.lang.reflect.MethodSignature 7 | import org.springframework.beans.factory.annotation.Autowired 8 | import org.springframework.context.annotation.Configuration 9 | 10 | @Aspect 11 | @Configuration 12 | class ScheduledJobTrackingAspect @Autowired constructor( 13 | private val scheduledJobTracker: ScheduledJobTracker 14 | ) { 15 | 16 | @Around("@annotation(org.springframework.scheduling.annotation.Scheduled)") 17 | fun around(joinPoint: ProceedingJoinPoint) { 18 | val signature = joinPoint.signature as MethodSignature 19 | 20 | val uuid = scheduledJobTracker.jobStart(signature) 21 | var exception: Throwable? = null 22 | 23 | try { 24 | joinPoint.proceed() 25 | } catch (t: Throwable) { 26 | exception = t 27 | } 28 | 29 | scheduledJobTracker.jobEnd(uuid, signature, exception) 30 | if (exception != null) 31 | throw exception 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/tracking/TrackedScheduledJob.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.tracking 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude 4 | import com.fasterxml.jackson.annotation.JsonProperty 5 | import java.time.Duration 6 | import java.time.Instant 7 | import java.util.* 8 | 9 | @JsonInclude(JsonInclude.Include.NON_NULL) 10 | data class TrackedScheduledJob( 11 | val className: String, 12 | val methodName: String, 13 | val settings: Settings, 14 | val stats: Stats = Stats(), 15 | val runs: MutableList = ArrayList() 16 | ) { 17 | 18 | private val trackingLimit = 10 19 | 20 | fun addRun(run: ScheduledJobRun) { 21 | stats.numberOfInvocations++ 22 | if (runs.size == trackingLimit) 23 | runs.removeAt(trackingLimit - 1) 24 | runs.add(0, run) 25 | } 26 | 27 | fun endRun(uuid: UUID, exception: Throwable?) { 28 | val endedAt = Instant.now() 29 | val run = runs.find { it.uuid == uuid } ?: return 30 | 31 | val index = runs.indexOf(run) 32 | runs.remove(run) 33 | runs.add(index, run.copy(endedAt = endedAt, exception = exception)) 34 | 35 | if (exception != null) 36 | stats.numberOfExceptions++ 37 | 38 | val durationInMillis = Duration.between(run.startedAt, endedAt).toMillis() 39 | stats.totalTimeInMs += durationInMillis 40 | if (stats.shortestRunDurationInMs == null || durationInMillis < stats.shortestRunDurationInMs!!) 41 | stats.shortestRunDurationInMs = durationInMillis 42 | if (stats.longestRunDurationInMs == null || durationInMillis > stats.longestRunDurationInMs!!) 43 | stats.longestRunDurationInMs = durationInMillis 44 | } 45 | 46 | @JsonProperty 47 | fun lastFinishedRun(): ScheduledJobRun? { 48 | return runs.filter { it.endedAt != null }.sortedByDescending { it.startedAt }.firstOrNull() 49 | } 50 | 51 | @JsonProperty 52 | fun latestRun(): ScheduledJobRun? { 53 | return runs.sortedByDescending { it.startedAt }.firstOrNull() 54 | } 55 | 56 | @JsonProperty("currentlyRunning") 57 | fun currentlyRunning(): Boolean { 58 | return runs.any { it.endedAt == null } 59 | } 60 | 61 | } 62 | 63 | data class Settings( 64 | val cron: String?, 65 | val fixedRate: Long?, 66 | val fixedRateString: String?, 67 | val initialDelay: Long?, 68 | val initialDelayString: String?, 69 | val fixedDelay: Long?, 70 | val fixedDelayString: String? 71 | ) 72 | 73 | data class Stats( 74 | var numberOfExceptions: Long = 0, 75 | var numberOfInvocations: Long = 0, 76 | var longestRunDurationInMs: Long? = null, 77 | var shortestRunDurationInMs: Long? = null, 78 | var totalTimeInMs: Long = 0 79 | ) { 80 | 81 | @JsonProperty 82 | fun averageDurationInMs(): Long? { 83 | if (numberOfInvocations == 0L) 84 | return null 85 | return totalTimeInMs / numberOfInvocations 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # tracking.scheduledJobs.path: /scheduled-jobs -------------------------------------------------------------------------------- /src/test/kotlin/com/example/demo/DemoApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.junit.Test 4 | import org.junit.runner.RunWith 5 | import org.springframework.boot.test.context.SpringBootTest 6 | import org.springframework.test.context.junit4.SpringRunner 7 | 8 | @RunWith(SpringRunner::class) 9 | @SpringBootTest 10 | class DemoApplicationTests { 11 | 12 | @Test 13 | fun contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------