0
# Configuration and Utilities
1
2
Enums, constants, and utility classes for job execution strategies, script types, system configuration, and helper functions.
3
4
## Capabilities
5
6
### ExecutorBlockStrategyEnum
7
8
Defines strategies for handling job execution when a job is already running.
9
10
```java { .api }
11
/**
12
* Strategies for handling job execution blocking
13
* Determines behavior when job is triggered while already running
14
*/
15
public enum ExecutorBlockStrategyEnum {
16
17
/**
18
* Serial execution - wait for current job to finish before starting new one
19
*/
20
SERIAL_EXECUTION("Serial execution"),
21
22
/**
23
* Discard later - ignore new trigger if job is already running
24
*/
25
DISCARD_LATER("Discard Later"),
26
27
/**
28
* Cover early - stop current job and start new one
29
*/
30
COVER_EARLY("Cover Early");
31
32
/**
33
* Get human-readable title for the strategy
34
* @return Strategy description
35
*/
36
public String getTitle();
37
38
/**
39
* Match strategy by name with fallback
40
* @param name Strategy name to match
41
* @param defaultItem Default strategy if no match found
42
* @return Matched strategy or default
43
*/
44
public static ExecutorBlockStrategyEnum match(String name, ExecutorBlockStrategyEnum defaultItem);
45
}
46
```
47
48
**Usage Examples:**
49
50
```java
51
// Configure job with specific blocking strategy
52
@XxlJob("serialJob")
53
public void serialJobHandler() throws Exception {
54
// This job will use SERIAL_EXECUTION by default
55
// Configure via admin interface for other strategies
56
57
XxlJobHelper.log("Job started - will block concurrent executions");
58
59
// Long-running job logic
60
Thread.sleep(30000); // 30 seconds
61
62
XxlJobHelper.handleSuccess();
63
}
64
65
// Check blocking strategy programmatically
66
public void checkBlockingStrategy(String strategyName) {
67
ExecutorBlockStrategyEnum strategy = ExecutorBlockStrategyEnum.match(
68
strategyName,
69
ExecutorBlockStrategyEnum.SERIAL_EXECUTION
70
);
71
72
System.out.println("Using strategy: " + strategy.getTitle());
73
}
74
```
75
76
### GlueTypeEnum
77
78
Supported script types for dynamic job execution through the glue mechanism.
79
80
```java { .api }
81
/**
82
* Supported script types for glue-based dynamic job execution
83
* Allows runtime job definition without redeployment
84
*/
85
public enum GlueTypeEnum {
86
87
/**
88
* Java bean method (default)
89
*/
90
BEAN("BEAN", false, null, null),
91
92
/**
93
* Embedded Java/Groovy code (not external script)
94
*/
95
GLUE_GROOVY("GLUE(Java)", false, null, null),
96
97
/**
98
* Shell script
99
*/
100
GLUE_SHELL("GLUE(Shell)", true, "bash", ".sh"),
101
102
/**
103
* Python script
104
*/
105
GLUE_PYTHON("GLUE(Python)", true, "python", ".py"),
106
107
/**
108
* PHP script
109
*/
110
GLUE_PHP("GLUE(PHP)", true, "php", ".php"),
111
112
/**
113
* Node.js script
114
*/
115
GLUE_NODEJS("GLUE(Nodejs)", true, "node", ".js"),
116
117
/**
118
* PowerShell script
119
*/
120
GLUE_POWERSHELL("GLUE(PowerShell)", true, "powershell", ".ps1");
121
122
/**
123
* Get human-readable description
124
* @return Script type description
125
*/
126
public String getDesc();
127
128
/**
129
* Check if this is a script type (vs bean type)
130
* @return true if script type, false for bean
131
*/
132
public boolean isScript();
133
134
/**
135
* Get command prefix for script execution
136
* @return Command to execute script or null for bean
137
*/
138
public String getCmd();
139
140
/**
141
* Get file extension for script type
142
* @return File extension or null for bean
143
*/
144
public String getSuffix();
145
146
/**
147
* Match glue type by name
148
* @param name Glue type name to match
149
* @return Matched glue type or null if not found
150
*/
151
public static GlueTypeEnum match(String name);
152
}
153
```
154
155
**Usage Examples:**
156
157
```java
158
// Check glue type capabilities
159
public void analyzeGlueType(String glueTypeName) {
160
GlueTypeEnum glueType = GlueTypeEnum.match(glueTypeName);
161
162
if (glueType != null) {
163
System.out.println("Type: " + glueType.getDesc());
164
System.out.println("Is Script: " + glueType.isScript());
165
166
if (glueType.isScript()) {
167
System.out.println("Command: " + glueType.getCmd());
168
System.out.println("File Extension: " + glueType.getSuffix());
169
}
170
}
171
}
172
173
// Example script content handling
174
public void prepareScriptExecution(GlueTypeEnum glueType, String scriptContent) {
175
if (glueType.isScript()) {
176
String filename = "job_script" + glueType.getSuffix();
177
String command = glueType.getCmd() + " " + filename;
178
179
// Write script to file and execute
180
writeScriptFile(filename, scriptContent);
181
executeCommand(command);
182
}
183
}
184
```
185
186
### RegistryConfig
187
188
Configuration constants and types for executor-admin registry communication.
189
190
```java { .api }
191
/**
192
* Registry configuration constants and types
193
* Defines timeouts and registry types for executor-admin communication
194
*/
195
public class RegistryConfig {
196
197
/**
198
* Heartbeat timeout in seconds
199
* Time between heartbeat signals from executor to admin
200
*/
201
public static final int BEAT_TIMEOUT = 30;
202
203
/**
204
* Dead timeout in seconds (3 times heartbeat timeout)
205
* Time after which executor is considered dead if no heartbeat received
206
*/
207
public static final int DEAD_TIMEOUT = BEAT_TIMEOUT * 3;
208
209
/**
210
* Registry types for different components
211
*/
212
public enum RegistType {
213
/**
214
* Executor registration type
215
*/
216
EXECUTOR,
217
218
/**
219
* Admin server registration type
220
*/
221
ADMIN
222
}
223
}
224
```
225
226
**Usage Examples:**
227
228
```java
229
// Configure heartbeat monitoring
230
public class HeartbeatMonitor {
231
232
public void startMonitoring() {
233
int heartbeatInterval = RegistryConfig.BEAT_TIMEOUT * 1000; // Convert to milliseconds
234
int deadThreshold = RegistryConfig.DEAD_TIMEOUT * 1000;
235
236
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
237
238
// Send heartbeat every BEAT_TIMEOUT seconds
239
scheduler.scheduleAtFixedRate(() -> {
240
sendHeartbeat();
241
}, 0, heartbeatInterval, TimeUnit.MILLISECONDS);
242
243
// Check for dead executors every DEAD_TIMEOUT seconds
244
scheduler.scheduleAtFixedRate(() -> {
245
checkDeadExecutors(deadThreshold);
246
}, deadThreshold, deadThreshold, TimeUnit.MILLISECONDS);
247
}
248
}
249
250
// Registry type usage
251
public void registerComponent(RegistryConfig.RegistType type, String key, String value) {
252
RegistryParam param = new RegistryParam(type.name(), key, value);
253
254
switch (type) {
255
case EXECUTOR:
256
System.out.println("Registering executor: " + key + " -> " + value);
257
break;
258
case ADMIN:
259
System.out.println("Registering admin: " + key + " -> " + value);
260
break;
261
}
262
}
263
```
264
265
### GlueFactory
266
267
Factory for creating and managing glue-based job handlers with dynamic script execution.
268
269
```java { .api }
270
/**
271
* Factory for creating glue job handlers
272
* Manages dynamic script compilation and execution
273
*/
274
public class GlueFactory {
275
276
/**
277
* Create glue job handler for given glue type and source
278
* @param glueType Glue type (BEAN, GLUE_GROOVY for embedded code, or script types like Shell, Python, etc.)
279
* @param glueSource Glue source code
280
* @return IJobHandler instance for glue execution
281
*/
282
public static IJobHandler getInstance(GlueTypeEnum glueType, String glueSource);
283
284
/**
285
* Refresh glue job handler cache
286
* Forces recompilation of script handlers
287
*/
288
public static void refreshInstance();
289
}
290
```
291
292
## Utility Classes
293
294
### XxlJobFileAppender
295
296
File-based logging utilities for job execution with automatic rotation and cleanup.
297
298
```java { .api }
299
/**
300
* File-based logging utilities for job execution
301
* Handles log file creation, rotation, and cleanup
302
*/
303
public class XxlJobFileAppender {
304
305
/**
306
* Initialize log path for job logging
307
* @param logPath Base directory for log files
308
*/
309
public static void initLogPath(String logPath);
310
311
/**
312
* Get current log base path
313
* @return Base directory for log files
314
*/
315
public static String getLogPath();
316
317
/**
318
* Get glue source code storage path
319
* @return Directory for storing glue scripts
320
*/
321
public static String getGlueSrcPath();
322
323
/**
324
* Generate log filename for specific job execution
325
* @param triggerDate Job trigger date
326
* @param logId Unique log identifier
327
* @return Generated log filename
328
*/
329
public static String makeLogFileName(Date triggerDate, long logId);
330
331
/**
332
* Append log content to job log file
333
* @param logFileName Target log file name
334
* @param appendLog Content to append
335
*/
336
public static void appendLog(String logFileName, String appendLog);
337
338
/**
339
* Read log content from specific line number
340
* @param logFileName Log file to read
341
* @param fromLineNum Starting line number (1-based)
342
* @return LogResult containing log content and metadata
343
*/
344
public static LogResult readLog(String logFileName, int fromLineNum);
345
346
/**
347
* Read all lines from log file
348
* @param logFile Log file to read
349
* @return Complete file content as string
350
*/
351
public static String readLines(File logFile);
352
}
353
```
354
355
**Usage Examples:**
356
357
```java
358
// Initialize logging system
359
XxlJobFileAppender.initLogPath("/var/log/xxl-job");
360
361
// Generate log filename
362
Date now = new Date();
363
long logId = 123456L;
364
String logFileName = XxlJobFileAppender.makeLogFileName(now, logId);
365
366
// Append to log
367
XxlJobFileAppender.appendLog(logFileName, "Job started at " + now);
368
XxlJobFileAppender.appendLog(logFileName, "Processing data...");
369
370
// Read log content
371
LogResult logResult = XxlJobFileAppender.readLog(logFileName, 1);
372
System.out.println("Log content: " + logResult.getLogContent());
373
```
374
375
### DateUtil
376
377
Date handling utilities for job scheduling and log management.
378
379
```java { .api }
380
/**
381
* Date utility functions for job scheduling
382
*/
383
public class DateUtil {
384
// Standard date formatting and parsing utilities
385
// Implementation varies - check source for specific methods
386
}
387
```
388
389
### FileUtil
390
391
File operation utilities for log management and script handling.
392
393
```java { .api }
394
/**
395
* File operation utilities
396
*/
397
public class FileUtil {
398
// File I/O operations, directory management
399
// Implementation varies - check source for specific methods
400
}
401
```
402
403
### GsonTool
404
405
JSON processing utilities using Google Gson for parameter serialization.
406
407
```java { .api }
408
/**
409
* JSON processing utilities using Gson
410
*/
411
public class GsonTool {
412
// JSON serialization and deserialization methods
413
// Implementation varies - check source for specific methods
414
}
415
```
416
417
### IpUtil
418
419
Network IP address utilities for executor registration and communication.
420
421
```java { .api }
422
/**
423
* Network IP address utilities
424
*/
425
public class IpUtil {
426
// IP address detection and validation methods
427
// Implementation varies - check source for specific methods
428
}
429
```
430
431
### NetUtil
432
433
Network communication utilities for HTTP client operations.
434
435
```java { .api }
436
/**
437
* Network communication utilities
438
*/
439
public class NetUtil {
440
// HTTP client operations, network connectivity checks
441
// Implementation varies - check source for specific methods
442
}
443
```
444
445
### ScriptUtil
446
447
Script execution utilities for running glue scripts in various languages.
448
449
```java { .api }
450
/**
451
* Script execution utilities for glue jobs
452
*/
453
public class ScriptUtil {
454
// Script execution, process management
455
// Implementation varies - check source for specific methods
456
}
457
```
458
459
### ThrowableUtil
460
461
Exception handling utilities for error processing and logging.
462
463
```java { .api }
464
/**
465
* Exception handling and stack trace utilities
466
*/
467
public class ThrowableUtil {
468
// Stack trace processing, exception formatting
469
// Implementation varies - check source for specific methods
470
}
471
```
472
473
### XxlJobRemotingUtil
474
475
Remote communication utilities for admin-executor RPC operations.
476
477
```java { .api }
478
/**
479
* Remote communication utilities for RPC operations
480
*/
481
public class XxlJobRemotingUtil {
482
// HTTP-based RPC communication, request/response handling
483
// Implementation varies - check source for specific methods
484
}
485
```
486
487
## Configuration Best Practices
488
489
### Production Configuration Values
490
491
```java
492
// Recommended production timeouts
493
public class ProductionConfig {
494
495
// Heartbeat configuration
496
public static final int PRODUCTION_BEAT_TIMEOUT = 30; // seconds
497
public static final int PRODUCTION_DEAD_TIMEOUT = 90; // 3x heartbeat
498
499
// Log retention
500
public static final int PRODUCTION_LOG_RETENTION_DAYS = 7;
501
502
// Job execution timeouts
503
public static final int DEFAULT_JOB_TIMEOUT = 300; // 5 minutes
504
public static final int LONG_RUNNING_JOB_TIMEOUT = 3600; // 1 hour
505
506
// Blocking strategies by job type
507
public static final ExecutorBlockStrategyEnum CRITICAL_JOB_STRATEGY =
508
ExecutorBlockStrategyEnum.SERIAL_EXECUTION;
509
public static final ExecutorBlockStrategyEnum BATCH_JOB_STRATEGY =
510
ExecutorBlockStrategyEnum.DISCARD_LATER;
511
public static final ExecutorBlockStrategyEnum REAL_TIME_JOB_STRATEGY =
512
ExecutorBlockStrategyEnum.COVER_EARLY;
513
}
514
```
515
516
### Environment-Specific Configurations
517
518
```java
519
@Configuration
520
public class EnvironmentJobConfig {
521
522
@Value("${environment:development}")
523
private String environment;
524
525
@Bean
526
public ExecutorBlockStrategyEnum defaultBlockingStrategy() {
527
switch (environment.toLowerCase()) {
528
case "production":
529
return ExecutorBlockStrategyEnum.SERIAL_EXECUTION;
530
case "staging":
531
return ExecutorBlockStrategyEnum.DISCARD_LATER;
532
case "development":
533
default:
534
return ExecutorBlockStrategyEnum.COVER_EARLY;
535
}
536
}
537
538
@Bean
539
public int logRetentionDays() {
540
switch (environment.toLowerCase()) {
541
case "production":
542
return 30;
543
case "staging":
544
return 7;
545
case "development":
546
default:
547
return 3;
548
}
549
}
550
}
551
```
552
553
### Glue Script Management
554
555
```java
556
public class GlueScriptManager {
557
558
public void deployScript(String jobHandler, GlueTypeEnum glueType, String scriptContent) {
559
// Validate script type
560
if (!glueType.isScript()) {
561
throw new IllegalArgumentException("Only script types allowed");
562
}
563
564
// Create script file
565
String filename = jobHandler + glueType.getSuffix();
566
String scriptPath = XxlJobFileAppender.getGlueSrcPath() + "/" + filename;
567
568
try {
569
// Write script to file
570
Files.write(Paths.get(scriptPath), scriptContent.getBytes());
571
572
// Set executable permissions for shell scripts
573
if (glueType == GlueTypeEnum.GLUE_SHELL) {
574
File scriptFile = new File(scriptPath);
575
scriptFile.setExecutable(true);
576
}
577
578
// Refresh glue factory to pick up changes
579
GlueFactory.refreshInstance();
580
581
System.out.println("Script deployed: " + filename);
582
583
} catch (IOException e) {
584
throw new RuntimeException("Failed to deploy script: " + e.getMessage(), e);
585
}
586
}
587
588
public void validateScript(GlueTypeEnum glueType, String scriptContent) {
589
switch (glueType) {
590
case GLUE_GROOVY:
591
// GLUE_GROOVY is embedded Java/Groovy code, not an external script
592
validateGroovyCode(scriptContent);
593
break;
594
case GLUE_SHELL:
595
validateShellScript(scriptContent);
596
break;
597
case GLUE_PYTHON:
598
validatePythonScript(scriptContent);
599
break;
600
default:
601
// Basic syntax check for other types
602
if (scriptContent == null || scriptContent.trim().isEmpty()) {
603
throw new IllegalArgumentException("Script content cannot be empty");
604
}
605
}
606
}
607
}
608
```