0
# Job Handlers and Annotations
1
2
Core job definition system using annotations and handler interfaces. Provides the foundation for creating executable job units that can be scheduled and triggered by the XXL-Job admin system.
3
4
## Capabilities
5
6
### @XxlJob Annotation
7
8
Primary annotation for marking methods as job handlers with automatic discovery by the Spring executor.
9
10
```java { .api }
11
/**
12
* Marks a method as a job handler for XXL-Job scheduling
13
* @param value - Job handler name (required, used for job registration)
14
* @param init - Init method name (optional, called when JobThread initializes)
15
* @param destroy - Destroy method name (optional, called when JobThread destroys)
16
*/
17
@Target({ElementType.METHOD})
18
@Retention(RetentionPolicy.RUNTIME)
19
@Inherited
20
public @interface XxlJob {
21
String value();
22
String init() default "";
23
String destroy() default "";
24
}
25
```
26
27
**Usage Examples:**
28
29
```java
30
import com.xxl.job.core.handler.annotation.XxlJob;
31
import com.xxl.job.core.context.XxlJobHelper;
32
import org.springframework.stereotype.Component;
33
34
@Component
35
public class SampleJobHandler {
36
37
// Basic job handler
38
@XxlJob("basicJob")
39
public void basicJobHandler() throws Exception {
40
String param = XxlJobHelper.getJobParam();
41
XxlJobHelper.log("Executing basic job with param: {}", param);
42
43
// Job logic here
44
45
XxlJobHelper.handleSuccess();
46
}
47
48
// Job with lifecycle methods
49
@XxlJob(value = "lifecycleJob", init = "initMethod", destroy = "cleanupMethod")
50
public void lifecycleJobHandler() throws Exception {
51
XxlJobHelper.log("Lifecycle job executing");
52
XxlJobHelper.handleSuccess();
53
}
54
55
public void initMethod() {
56
XxlJobHelper.log("Job initialization");
57
}
58
59
public void cleanupMethod() {
60
XxlJobHelper.log("Job cleanup");
61
}
62
63
// Sharded job example
64
@XxlJob("shardedJob")
65
public void shardedJobHandler() throws Exception {
66
int shardIndex = XxlJobHelper.getShardIndex();
67
int shardTotal = XxlJobHelper.getShardTotal();
68
69
XxlJobHelper.log("Processing shard {} of {}", shardIndex, shardTotal);
70
71
// Process only data for this shard
72
for (int i = shardIndex; i < dataList.size(); i += shardTotal) {
73
// Process dataList.get(i)
74
}
75
76
XxlJobHelper.handleSuccess();
77
}
78
}
79
```
80
81
### IJobHandler Abstract Class
82
83
Base abstract class for creating custom job handlers when annotation-based approach is not suitable.
84
85
```java { .api }
86
/**
87
* Base abstract class for job handlers
88
* Provides lifecycle methods for job execution
89
*/
90
public abstract class IJobHandler {
91
/**
92
* Execute the job handler
93
* Must be implemented by subclasses
94
* @throws Exception if job execution fails
95
*/
96
public abstract void execute() throws Exception;
97
98
/**
99
* Initialize the job handler
100
* Called when JobThread is created
101
* @throws Exception if initialization fails
102
*/
103
public void init() throws Exception {
104
// Default empty implementation
105
}
106
107
/**
108
* Cleanup the job handler
109
* Called when JobThread is destroyed
110
* @throws Exception if cleanup fails
111
*/
112
public void destroy() throws Exception {
113
// Default empty implementation
114
}
115
}
116
```
117
118
**Usage Examples:**
119
120
```java
121
import com.xxl.job.core.handler.IJobHandler;
122
import com.xxl.job.core.context.XxlJobHelper;
123
124
// Custom job handler implementation
125
public class CustomJobHandler extends IJobHandler {
126
127
private SomeService service;
128
129
@Override
130
public void init() throws Exception {
131
// Initialize resources
132
service = new SomeService();
133
XxlJobHelper.log("CustomJobHandler initialized");
134
}
135
136
@Override
137
public void execute() throws Exception {
138
try {
139
String param = XxlJobHelper.getJobParam();
140
XxlJobHelper.log("Processing with param: {}", param);
141
142
// Execute job logic
143
service.processData(param);
144
145
XxlJobHelper.handleSuccess("Job completed successfully");
146
} catch (Exception e) {
147
XxlJobHelper.log(e);
148
XxlJobHelper.handleFail("Job failed: " + e.getMessage());
149
}
150
}
151
152
@Override
153
public void destroy() throws Exception {
154
// Cleanup resources
155
if (service != null) {
156
service.close();
157
}
158
XxlJobHelper.log("CustomJobHandler destroyed");
159
}
160
}
161
162
// Register custom handler programmatically
163
XxlJobExecutor.registJobHandler("customJobHandler", new CustomJobHandler());
164
```
165
166
### Method Job Handler Implementation
167
168
Internal implementation used by the framework for @XxlJob annotated methods.
169
170
```java { .api }
171
/**
172
* Internal job handler implementation for annotated methods
173
* Used by the framework to wrap @XxlJob annotated methods
174
*/
175
public class MethodJobHandler extends IJobHandler {
176
// Framework internal - not for direct use
177
}
178
```
179
180
### Script Job Handler Implementation
181
182
Implementation for dynamic script-based job execution supporting multiple scripting languages.
183
184
```java { .api }
185
/**
186
* Job handler for script-based job execution
187
* Supports Groovy, Shell, Python, PHP, Node.js, PowerShell
188
*/
189
public class ScriptJobHandler extends IJobHandler {
190
// Framework internal - scripts managed through admin interface
191
}
192
```
193
194
### Glue Job Handler Implementation
195
196
Implementation for dynamically loaded job code ("glue" jobs) that can be updated at runtime.
197
198
```java { .api }
199
/**
200
* Job handler for glue-type jobs
201
* Allows runtime code updates without redeployment
202
*/
203
public class GlueJobHandler extends IJobHandler {
204
// Framework internal - glue code managed through admin interface
205
}
206
```
207
208
## Job Handler Registration
209
210
### Automatic Registration (Spring)
211
212
When using `XxlJobSpringExecutor`, all `@XxlJob` annotated methods in Spring beans are automatically discovered and registered:
213
214
```java
215
@Configuration
216
public class XxlJobConfig {
217
218
@Bean
219
public XxlJobSpringExecutor xxlJobExecutor() {
220
XxlJobSpringExecutor executor = new XxlJobSpringExecutor();
221
// Configuration...
222
return executor;
223
// All @XxlJob methods automatically registered on startup
224
}
225
}
226
```
227
228
### Manual Registration (Standalone)
229
230
For non-Spring environments, register job handlers manually:
231
232
```java
233
// Register IJobHandler implementations
234
XxlJobExecutor.registJobHandler("myJobHandler", new MyJobHandler());
235
236
// For XxlJobSimpleExecutor, provide bean list
237
XxlJobSimpleExecutor executor = new XxlJobSimpleExecutor();
238
List<Object> jobBeans = Arrays.asList(new MyJobHandlerBean());
239
executor.setXxlJobBeanList(jobBeans);
240
```
241
242
## Job Handler Best Practices
243
244
### Error Handling
245
246
```java
247
@XxlJob("robustJob")
248
public void robustJobHandler() throws Exception {
249
try {
250
String param = XxlJobHelper.getJobParam();
251
252
// Validate parameters
253
if (param == null || param.trim().isEmpty()) {
254
XxlJobHelper.handleFail("Job parameter is required");
255
return;
256
}
257
258
// Execute job logic with proper error handling
259
processData(param);
260
261
XxlJobHelper.handleSuccess("Job completed successfully");
262
263
} catch (BusinessException e) {
264
XxlJobHelper.log("Business error: {}", e.getMessage());
265
XxlJobHelper.handleFail("Business error: " + e.getMessage());
266
} catch (Exception e) {
267
XxlJobHelper.log(e);
268
XxlJobHelper.handleFail("Unexpected error: " + e.getMessage());
269
}
270
}
271
```
272
273
### Parameter Processing
274
275
```java
276
@XxlJob("parameterizedJob")
277
public void parameterizedJobHandler() throws Exception {
278
String param = XxlJobHelper.getJobParam();
279
280
// Parse JSON parameters
281
ObjectMapper mapper = new ObjectMapper();
282
JobParams params = mapper.readValue(param, JobParams.class);
283
284
XxlJobHelper.log("Processing with params: startDate={}, endDate={}",
285
params.getStartDate(), params.getEndDate());
286
287
// Use parameters in job logic
288
processDateRange(params.getStartDate(), params.getEndDate());
289
290
XxlJobHelper.handleSuccess();
291
}
292
```
293
294
### Logging and Monitoring
295
296
```java
297
@XxlJob("monitoredJob")
298
public void monitoredJobHandler() throws Exception {
299
long startTime = System.currentTimeMillis();
300
XxlJobHelper.log("Job started at {}", new Date());
301
302
try {
303
// Job logic with progress logging
304
int totalItems = getItemCount();
305
XxlJobHelper.log("Processing {} items", totalItems);
306
307
for (int i = 0; i < totalItems; i++) {
308
processItem(i);
309
310
// Log progress periodically
311
if (i % 100 == 0) {
312
XxlJobHelper.log("Processed {}/{} items", i, totalItems);
313
}
314
}
315
316
long duration = System.currentTimeMillis() - startTime;
317
XxlJobHelper.handleSuccess("Processed " + totalItems + " items in " + duration + "ms");
318
319
} catch (Exception e) {
320
long duration = System.currentTimeMillis() - startTime;
321
XxlJobHelper.log("Job failed after {}ms: {}", duration, e.getMessage());
322
XxlJobHelper.handleFail(e.getMessage());
323
}
324
}
325
```