Creating your own Crontab job
Application support jobs written in BeanShell or classes into JAR file. We recommend the use JAR files instead of BeanShell.
Understanding the crontab job execution context
Execution context:
- Crontab job is executed by internall users named "system" ( the job has not a valid user session ).
- Crontab job is executed by administrator user ( the job has a valid user session ).
All API methods have variable named token.
When user is logged the call to the API use token value to null. That indicates application must use the logged session.
When user is not logged, the call to the API must use a not null token, otherwise will get an error.
Example of use:
- logged user -> valid API call -> OKMFolder.getInstance().createSimple(null, "/okm:root/test");
- not logged user -> invalid API call -> OKMFolder.getInstance().createSimple(null, "/okm:root/test");
Use the system token is a good practice when calling API methods into crontab task:
String systemToken = DbSessionManager.getInstance().getSystemsystemToken();
OKMFolder.getInstance().createSimple(systemToken, "/okm:root/test")
Crontab job based on JAR file
Requisits:
- Must implement the class "public static void main(String[] args)".
package com.openkm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.module.db.stuff.DbSessionManager;
public class CronTabTest {
private static Logger log = LoggerFactory.getLogger(CronTabTest.class);
public static void main(String[] args) {
System.out.println(cronTask(DbSessionManager.getInstance().getSystemToken()));
}
}
To create a JAR file follow the instructions Creating a JAR file with Eclipse.
Contab job based on BeanShell
Example import files from /home/scanner folder to /okm:root/Scans
Is a good practice test script from Scripting view, before registering.
In the script you have access to these variables:
- systemToken: The system token for this instance.
- crontabName: The name of the crontab defined to run this script.
- crontabId: The id of the crontab defined to run this script.
import com.openkm.module.db.stuff.*;
import com.openkm.core.*;
import com.openkm.api.OKMDocument;
import java.io.*;
String systemToken = DbSessionManager.getInstance().getSystemsystemToken();
OKMDocument document = OKMDocument.getInstance();
public class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
File scans = new File("/home/scanner");
Thread.sleep(10000); // Sleep 10 seconds in case files are still being written
try {
for (File scan : scans.listFiles(new OnlyExt("pdf"))) {
try {
document.createSimple(systemToken, "/okm:root/Scans/" + scan.getName(), new FileInputStream(scan));
scan.delete();
} catch (Exception e) {
print("Exception: " + e);
}
}
} catch (Exception e) {
print("Exception: " + e);
}