Skip to content

Instantly share code, notes, and snippets.

@nilsmagnus
Last active August 31, 2019 20:45
Show Gist options
  • Save nilsmagnus/8103287 to your computer and use it in GitHub Desktop.
Save nilsmagnus/8103287 to your computer and use it in GitHub Desktop.
Appengine executorservice usage
package no.nilsapp.someapp.cronjobs;
import com.google.appengine.api.ThreadManager;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class AppengineExecutor {
public void run() throws IOException {
ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
ExecutorService executor = Executors.newCachedThreadPool(factory);
List<Shipment> shipmentsToCheck = dataStorage.getShipmentsNotDelivered();
System.out.println("Checking shipments " + shipmentsToCheck.size());
for (Shipment shipment : shipmentsToCheck) {
// please note that "MyRunnable" implements Runnable and cannot directly extend Thread.
Runnable checkShipmentTask = ThreadManager.createThreadForCurrentRequest(new MyRunnable(shipment));
executor.execute(checkShipmentTask);
}
System.out.println("Sent all jobs to execution.");
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment