This section includes source code for all of the Gurobi batch mode examples.The same source code can be found in theexamples directory of theGurobi distribution.
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads a MIP model from a file, solves it in batch mode, * and prints the JSON solution string. */#include<assert.h>#include<stdlib.h>#include<stdio.h>#include<time.h>#include<string.h>#if defined (WIN32) || defined (WIN64)#include<Windows.h>#define sleep(n) Sleep(1000*n)#else#include<unistd.h>#endif#include"gurobi_c.h"/* setup gurobi environment */intsetupbatchconnection(GRBenv**envP){interror=0;GRBenv*env=NULL;/* setup a batch environment */error=GRBemptyenv(envP);if(error)gotoQUIT;env=*envP;error=GRBsetintparam(env,"CSBatchMode",1);if(error)gotoQUIT;error=GRBsetstrparam(env,"LogFile","batchmode.log");if(error)gotoQUIT;error=GRBsetstrparam(env,"CSManager","http://localhost:61080");if(error)gotoQUIT;error=GRBsetstrparam(env,"UserName","gurobi");if(error)gotoQUIT;error=GRBsetstrparam(env,"ServerPassword","pass");if(error)gotoQUIT;error=GRBstartenv(env);if(error)gotoQUIT;QUIT:if(error){printf("Failed to setup environment, error code %d\n",error);}else{printf("Successfully created environment\n");}returnerror;}/* display batch-error code if any */voidbatcherrorinfo(GRBbatch*batch){interror=0;interrorCode;char*errorMsg;char*BatchID;if(!batch)gotoQUIT;/* query the last error code */error=GRBgetbatchintattr(batch,"BatchErrorCode",&errorCode);if(error||!errorCode)gotoQUIT;/* query the last error message */error=GRBgetbatchstrattr(batch,"BatchErrorMessage",&errorMsg);if(error)gotoQUIT;error=GRBgetbatchstrattr(batch,"BatchID",&BatchID);if(error)gotoQUIT;printf("Batch ID %s Error Code %d (%s)\n",BatchID,errorCode,errorMsg);QUIT:return;}/* create a batch request for given problem file */intnewbatchrequest(constchar*filename,char*BatchID){interror=0;GRBenv*env=NULL;GRBenv*menv=NULL;GRBmodel*model=NULL;chartag[128];intcols,j;/* setup a batch connection */error=setupbatchconnection(&env);if(error)gotoQUIT;/* read a model */error=GRBreadmodel(env,filename,&model);if(error)gotoQUIT;/* set some params */menv=GRBgetenv(model);assert(menv!=NULL);error=GRBsetdblparam(menv,"MIPGap",0.01);if(error)gotoQUIT;/* for extra detailed information on JSON solution string */error=GRBsetintparam(menv,"JSONSolDetail",1);if(error)gotoQUIT;/* setup some tags, we need tags to be able to query results later on */error=GRBgetintattr(model,"NumVars",&cols);if(error)gotoQUIT;if(cols>10)cols=10;for(j=0;j<cols;j++){sprintf(tag,"MyUniqueVariableID%d",j);error=GRBsetstrattrelement(model,"VTag",j,tag);}/* submit batch request to the Manager */error=GRBoptimizebatch(model,BatchID);if(error)gotoQUIT;QUIT:if(error){printf("Failed to submit a new batch request, error code %d\n",error);}else{printf("Successfully submitted new batch request %s\n",BatchID);}GRBfreemodel(model);GRBfreeenv(env);returnerror;}/* wait for final bstatus */intwaitforfinalstatus(constchar*BatchID){interror=0;GRBenv*env=NULL;GRBbatch*batch=NULL;time_tstart,current;intbstatus;/* setup a batch connection */error=setupbatchconnection(&env);if(error)gotoQUIT;/* create batch-object */error=GRBgetbatch(env,BatchID,&batch);if(error)gotoQUIT;/* query bstatus, and wait for completed */error=GRBgetbatchintattr(batch,"BatchStatus",&bstatus);if(error)gotoQUIT;start=time(NULL);while(bstatus==GRB_BATCH_SUBMITTED){/* abort if taking too long */current=time(NULL);if(current-start>=3600){/* request to abort the batch */error=GRBabortbatch(batch);if(error)gotoQUIT;}/* do not bombard the server */sleep(1u);/* update local attributes */error=GRBupdatebatch(batch);if(error)gotoQUIT;/* query bstatus */error=GRBgetbatchintattr(batch,"BatchStatus",&bstatus);if(error)gotoQUIT;/* deal with failed bstatus */if(bstatus==GRB_BATCH_FAILED){/* retry the batch request */error=GRBretrybatch(batch);if(error)gotoQUIT;bstatus=GRB_BATCH_SUBMITTED;}}QUIT:if(error){printf("Failed to wait for final bstatus, error code %d\n",error);}else{printf("Final Batch Status %d\n",bstatus);}batcherrorinfo(batch);/* release local resources */GRBfreebatch(batch);GRBfreeenv(env);returnerror;}/* final report on batch request */intfinalreport(constchar*BatchID){interror=0;GRBenv*env=NULL;GRBbatch*batch=NULL;char*jsonsol=NULL;intbstatus;/* setup a batch connection */error=setupbatchconnection(&env);if(error)gotoQUIT;/* create batch object */error=GRBgetbatch(env,BatchID,&batch);if(error)gotoQUIT;/* query bstatus, and wait for completed */error=GRBgetbatchintattr(batch,"BatchStatus",&bstatus);if(error)gotoQUIT;/* display depending on batch bstatus */switch(bstatus){caseGRB_BATCH_CREATED:printf("Batch is 'CREATED'\n");printf("maybe batch-creation process was killed?\n");break;caseGRB_BATCH_SUBMITTED:printf("Batch is 'SUBMITTED'\n");printf("Some other user re-submitted this Batch object?\n");break;caseGRB_BATCH_ABORTED:printf("Batch is 'ABORTED'\n");break;caseGRB_BATCH_FAILED:printf("Batch is 'FAILED'\n");break;caseGRB_BATCH_COMPLETED:/* print JSON solution into string */error=GRBgetbatchjsonsolution(batch,&jsonsol);if(error)gotoQUIT;printf("JSON solution: %s\n",jsonsol);/* save solution into a file */error=GRBwritebatchjsonsolution(batch,"batch-sol.json.gz");if(error)gotoQUIT;break;default:printf("This should not happen, probably points to a"" user-memory corruption problem\n");exit(EXIT_FAILURE);break;}QUIT:if(error){printf("Failed to perform final report, error code %d\n",error);}else{printf("Reporting done\n");}batcherrorinfo(batch);if(jsonsol)GRBfree(jsonsol);GRBfreebatch(batch);GRBfreeenv(env);returnerror;}/* remove batch ID from manager */intdiscardbatch(constchar*BatchID){interror=0;GRBenv*env=NULL;GRBbatch*batch=NULL;/* setup a batch connection */error=setupbatchconnection(&env);if(error)gotoQUIT;/* create batch object */error=GRBgetbatch(env,BatchID,&batch);if(error)gotoQUIT;/* discard the batch object in the manager */error=GRBdiscardbatch(batch);if(error)gotoQUIT;QUIT:batcherrorinfo(batch);GRBfreebatch(batch);GRBfreeenv(env);returnerror;}intmain(intargc,char**argv){interror=0;charBatchID[GRB_MAX_STRLEN+1];/* ensure enough parameters */if(argc<2){fprintf(stderr,"Usage: %s filename\n",argv[0]);gotoQUIT;}/* create a new batch request */error=newbatchrequest(argv[1],BatchID);if(error)gotoQUIT;/* wait for final bstatus */error=waitforfinalstatus(BatchID);if(error)gotoQUIT;/* query final bstatus, and if completed, print JSON solution */error=finalreport(BatchID);if(error)gotoQUIT;/* eliminate batch from the manager */error=discardbatch(BatchID);if(error)gotoQUIT;QUIT:returnerror;}
/* Copyright 2025, Gurobi Optimization, LLC */// This example reads a MIP model from a file, solves it in batch mode,// and prints the JSON solution string.//// You will need a Compute Server license for this example to work.#include<ctime>#if defined (WIN32) || defined (WIN64) || defined(_WIN32) || defined (_WIN64)#include<Windows.h>#define sleep(n) Sleep(1000*n)#else#include<unistd.h>#endif#include"gurobi_c++.h"usingnamespacestd;// Set-up the environment for batch mode optimization.//// The function configures and start an environment to be used for batch// optimization.voidsetupbatchenv(GRBEnv*env){env->set(GRB_StringParam_LogFile,"batchmode.log");env->set(GRB_StringParam_CSManager,"http://localhost:61080");env->set(GRB_StringParam_UserName,"gurobi");env->set(GRB_StringParam_ServerPassword,"pass");env->set(GRB_IntParam_CSBatchMode,1);// No network communication happened up to this point. This will happen// now that we call the start() method.env->start();}// Print batch job error information, if anyvoidprintbatcherrorinfo(GRBBatch&batch){if(batch.get(GRB_IntAttr_BatchErrorCode)==0)return;cerr<<"Batch ID "<<batch.get(GRB_StringAttr_BatchID)<<": Error code "<<batch.get(GRB_IntAttr_BatchErrorCode)<<" ("<<batch.get(GRB_StringAttr_BatchErrorMessage)<<")"<<endl;}// Create a batch request for given problem filestringnewbatchrequest(char*filename){GRBEnv*env=NULL;GRBModel*model=NULL;GRBVar*v=NULL;stringbatchID;try{// Start environment, create Model object from fileenv=newGRBEnv(true);setupbatchenv(env);model=newGRBModel(*env,filename);// Set some parameters; switch on detailed JSON informationmodel->set(GRB_DoubleParam_MIPGap,0.01);model->set(GRB_IntParam_JSONSolDetail,1);// Define tags for some variables in order to access their values laterintnumvars=model->get(GRB_IntAttr_NumVars);v=model->getVars();if(numvars>10)numvars=10;for(intj=0;j<numvars;j++){charvtag[64];sprintf(vtag,"Variable %d",j);v[j].set(GRB_StringAttr_VTag,string(vtag));}// submit batch requestbatchID=model->optimizeBatch();}catch(...){// Free local resourcesdelete[]v;deletemodel;deleteenv;// Let the exception propagatethrow;}// Free local resourcesdelete[]v;deletemodel;deleteenv;returnbatchID;}// Wait for the final status of the batch.// Initially the status of a batch is "submitted"; the status will change// once the batch has been processed (by a compute server).voidwaitforfinalstatus(stringbatchID){// Wait no longer than one hourtime_tmaxwaittime=3600;GRBEnv*env=NULL;GRBBatch*batch=NULL;try{// Setup and start environment, create local Batch handle objectenv=newGRBEnv(true);setupbatchenv(env);batch=newGRBBatch(*env,batchID);time_tstarttime=time(NULL);intBatchStatus=batch->get(GRB_IntAttr_BatchStatus);while(BatchStatus==GRB_BATCH_SUBMITTED){// Abort this batch if it is taking too longtime_tcurtime=time(NULL);if(curtime-starttime>maxwaittime){batch->abort();break;}// Wait for two secondssleep(2);// Update the resident attribute cache of the Batch object with the// latest values from the cluster manager.batch->update();BatchStatus=batch->get(GRB_IntAttr_BatchStatus);// If the batch failed, we try againif(BatchStatus==GRB_BATCH_FAILED)batch->retry();}}catch(...){// Print information about error status of the job that// processed the batchprintbatcherrorinfo(*batch);// Free local resourcesdeletebatch;deleteenv;// let the exception propagatethrow;}// Free local resourcesdeletebatch;deleteenv;}voidprintfinalreport(stringbatchID){GRBEnv*env=NULL;GRBBatch*batch=NULL;try{// Setup and starts environment, create local Batch handle objectenv=newGRBEnv(true);setupbatchenv(env);batch=newGRBBatch(*env,batchID);intBatchStatus=batch->get(GRB_IntAttr_BatchStatus);if(BatchStatus==GRB_BATCH_CREATED)cout<<"Batch status is 'CREATED'"<<endl;elseif(BatchStatus==GRB_BATCH_SUBMITTED)cout<<"Batch is 'SUBMITTED"<<endl;elseif(BatchStatus==GRB_BATCH_ABORTED)cout<<"Batch is 'ABORTED'"<<endl;elseif(BatchStatus==GRB_BATCH_FAILED)cout<<"Batch is 'FAILED'"<<endl;elseif(BatchStatus==GRB_BATCH_COMPLETED){cout<<"Batch is 'COMPLETED'"<<endl;// Pretty printing the general solution informationcout<<"JSON solution:"<<batch->getJSONSolution()<<endl;// Write the full JSON solution string to a filebatch->writeJSONSolution("batch-sol.json.gz");}else{// Should not happencout<<"Batch has unknown BatchStatus"<<endl;}}catch(...){// Free local resourcesdeletebatch;deleteenv;// let the exception propagatethrow;}// Free local resourcesdeletebatch;deleteenv;}// Instruct cluster manager to remove all data relating to this BatchIDvoidbatchdiscard(stringbatchID){GRBEnv*env=NULL;GRBBatch*batch=NULL;try{// Setup and start environment, create local Batch handle objectenv=newGRBEnv(true);setupbatchenv(env);batch=newGRBBatch(*env,batchID);// Remove batch request from managerbatch->discard();}catch(...){// Free local resources evendeletebatch;deleteenv;// let the exception propagatethrow;}// Free local resourcesdeletebatch;deleteenv;}// Solve a given model using batch optimizationintmain(intargc,char**argv){// Ensure we have an input fileif(argc!=2){cout<<"Usage: "<<argv[0]<<" filename"<<endl;return0;}try{// Submit new batch requeststringbatchID=newbatchrequest(argv[1]);// Wait for final statuswaitforfinalstatus(batchID);// Report final status infoprintfinalreport(batchID);// Remove batch request from managerbatchdiscard(batchID);cout<<"Batch optimization OK"<<endl;}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Exception during optimization"<<endl;}return0;}
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads a MIP model from a file, solves it in batch mode, and prints the JSON solution string. You will need a Compute Server license for this example to work. */usingSystem;usingGurobi;classbatchmode_cs{/// <summary>Set-up the environment for batch mode optimization./// </summary>/// <remarks>/// The function creates an empty environment, sets all neccessary/// parameters, and returns the ready-to-be-started Env object to/// caller./// </remarks>staticvoidsetupbatchenv(refGRBEnvenv){env.CSBatchMode=1;env.CSManager="http://localhost:61080";env.LogFile="batchmode.log";env.ServerPassword="pass";env.UserName="gurobi";// No network communication happened up to this point. This will happen// now that we call start().env.Start();}///<summary>Print batch job error information, if any</summary>staticvoidprintbatcherrorinfo(refGRBBatchbatch){if(batch.BatchErrorCode==0)return;Console.WriteLine("Batch ID: "+batch.BatchID+", Error code: "+batch.BatchErrorCode+"("+batch.BatchErrorMessage+")");}///<summary>Create a batch request for given problem file</summary>staticstringnewbatchrequest(stringfilename){stringbatchID="";// Create an empty environmentGRBEnvenv=newGRBEnv(true);// set environment and build modelsetupbatchenv(refenv);GRBModelmodel=newGRBModel(env,filename);try{// Set some parametersmodel.Set(GRB.DoubleParam.MIPGap,0.01);model.Set(GRB.IntParam.JSONSolDetail,1);// Define tags for some variables to access their values laterintcount=0;foreach(GRBVarvinmodel.GetVars()){v.VTag="Variable"+count;count+=1;if(count>=10)break;}// Submit batch requestbatchID=model.OptimizeBatch();}finally{// Dispose of model and envmodel.Dispose();env.Dispose();}returnbatchID;}///<summary>Wait for the final status of the batch. Initially the/// status of a batch is <see cref="GRB.BatchStatus.SUBMITTED"/>;/// the status will change once the batch has been processed/// (by a compute server).</summary>staticvoidwaitforfinalstatus(stringbatchID){// Wait no longer than one hourdoublemaxwaittime=3600;DateTimestart=DateTime.Now;// Setup and start environment, create local Batch handle objectGRBEnvenv=newGRBEnv(true);setupbatchenv(refenv);GRBBatchbatch=newGRBBatch(env,batchID);try{while(batch.BatchStatus==GRB.BatchStatus.SUBMITTED){// Abort this batch if it is taking too longTimeSpaninterval=DateTime.Now-start;if(interval.TotalSeconds>maxwaittime){batch.Abort();break;}// Wait for two secondsSystem.Threading.Thread.Sleep(2000);// Update the resident attribute cache of the Batch object// with the latest values from the cluster manager.batch.Update();// If the batch failed, we retry itif(batch.BatchStatus==GRB.BatchStatus.FAILED){batch.Retry();System.Threading.Thread.Sleep(2000);batch.Update();}}}finally{// Print information about error status of the job// that processed the batchprintbatcherrorinfo(refbatch);batch.Dispose();env.Dispose();}}///<summary>Final Report for Batch Request</summary>staticvoidprintfinalreport(stringbatchID){// Setup and start environment, create local Batch handle objectGRBEnvenv=newGRBEnv(true);setupbatchenv(refenv);GRBBatchbatch=newGRBBatch(env,batchID);switch(batch.BatchStatus){caseGRB.BatchStatus.CREATED:Console.WriteLine("Batch status is 'CREATED'\n");break;caseGRB.BatchStatus.SUBMITTED:Console.WriteLine("Batch is 'SUBMITTED\n");break;caseGRB.BatchStatus.ABORTED:Console.WriteLine("Batch is 'ABORTED'\n");break;caseGRB.BatchStatus.FAILED:Console.WriteLine("Batch is 'FAILED'\n");break;caseGRB.BatchStatus.COMPLETED:Console.WriteLine("Batch is 'COMPLETED'\n");// Get JSON solution as stringConsole.WriteLine("JSON solution:"+batch.GetJSONSolution());// Write the full JSON solution string to a filebatch.WriteJSONSolution("batch-sol.json.gz");break;default:// Should not happenConsole.WriteLine("Unknown BatchStatus"+batch.BatchStatus);Environment.Exit(1);break;}// Cleanupbatch.Dispose();env.Dispose();}///<summary>Instruct the cluster manager to discard all data relating/// to this BatchID</summary>staticvoidbatchdiscard(stringbatchID){// Setup and start environment, create local Batch handle objectGRBEnvenv=newGRBEnv(true);setupbatchenv(refenv);GRBBatchbatch=newGRBBatch(env,batchID);// Remove batch request from managerbatch.Discard();// Cleanupbatch.Dispose();env.Dispose();}///<summary>Solve a given model using batch optimization</summary>staticvoidMain(string[]args){if(args.Length<1){Console.Out.WriteLine("Usage: batchmode_cs filename");return;}try{// Submit new batch requeststringbatchID=newbatchrequest(args[0]);// Wait for final statuswaitforfinalstatus(batchID);// Report final status infoprintfinalreport(batchID);// Remove batch request from managerbatchdiscard(batchID);Console.WriteLine("Batch optimization OK");}catch(GRBExceptione){Console.WriteLine("Error code: "+e.ErrorCode+". "+e.Message);}}}
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads a model from a file, solves it in batch mode * and prints the JSON solution string. */importcom.gurobi.gurobi.*;publicclassBatchmode{// Set-up a batch-mode environmentprivatestaticGRBEnvsetupbatchconnection()throwsGRBException{GRBEnvenv=newGRBEnv(true);env.set(GRB.IntParam.CSBatchMode,1);env.set(GRB.StringParam.LogFile,"batchmode.log");env.set(GRB.StringParam.CSManager,"http://localhost:61080");env.set(GRB.StringParam.UserName,"gurobi");env.set(GRB.StringParam.ServerPassword,"pass");env.start();returnenv;}// Display batch-error if anyprivatestaticvoidbatcherrorinfo(GRBBatchbatch)throwsGRBException{// Get last error codeinterror=batch.get(GRB.IntAttr.BatchErrorCode);if(error==0)return;// Query last error messageStringerrMsg=batch.get(GRB.StringAttr.BatchErrorMessage);// Query batchIDStringbatchID=batch.get(GRB.StringAttr.BatchID);System.out.println("Batch ID "+batchID+"Error Code "+error+"("+errMsg+")");}// Create a batch request from the given problem fileprivatestaticStringnewbatchrequest(Stringfilename)throwsGRBException{// Setup a batch connectionGRBEnvenv=setupbatchconnection();// Read a modelGRBModelmodel=newGRBModel(env,filename);// Set some parametersmodel.set(GRB.DoubleParam.MIPGap,0.01);model.set(GRB.IntParam.JSONSolDetail,1);// Set-up some tags, we need tags to be able to query resultsintcount=0;for(GRBVarv:model.getVars()){v.set(GRB.StringAttr.VTag,"UniqueVariableIdentifier"+count);count+=1;if(count>=10)break;}// Batch-mode optimizationStringbatchid=model.optimizeBatch();// no need to keep the model aroundmodel.dispose();// no need to keep environmentenv.dispose();returnbatchid;}// Wait for final statusprivatestaticvoidwaitforfinalstatus(Stringbatchid)throwsException{// Setup a batch connectionGRBEnvenv=setupbatchconnection();// Create Batch-objectGRBBatchbatch=newGRBBatch(env,batchid);try{// Query status, and wait for completedintstatus=batch.get(GRB.IntAttr.BatchStatus);longtimestart=System.currentTimeMillis();while(status==GRB.BatchStatus.SUBMITTED){// Abort if taking too longlongcurtime=System.currentTimeMillis();if(curtime-timestart>3600*1000){// Request to abort the batchbatch.abort();break;}// Do not bombard the serverThread.sleep(2000);// Update local attributesbatch.update();// Query current statusstatus=batch.get(GRB.IntAttr.BatchStatus);// Deal with failed statusif(status==GRB.BatchStatus.FAILED||status==GRB.BatchStatus.ABORTED){// Retry the batch jobbatch.retry();}}}catch(Exceptione){// Display batch-error if anybatcherrorinfo(batch);throwe;}finally{// Dispose resourcesbatch.dispose();env.dispose();}}// Final report on batch requestprivatestaticvoidfinalreport(Stringbatchid)throwsGRBException{// Setup a batch connectionGRBEnvenv=setupbatchconnection();// Create batch objectGRBBatchbatch=newGRBBatch(env,batchid);try{intstatus=batch.get(GRB.IntAttr.BatchStatus);// Display depending on batch statusswitch(status){caseGRB.BatchStatus.CREATED:System.out.println("Batch is 'CREATED'");System.out.println("maybe batch-creation process was killed?");break;caseGRB.BatchStatus.SUBMITTED:System.out.println("Batch is 'SUBMITTED'");System.out.println("Some other user re-submitted this Batch object?");break;caseGRB.BatchStatus.ABORTED:System.out.println("Batch is 'ABORTED'");break;caseGRB.BatchStatus.FAILED:System.out.println("Batch is 'FAILED'");break;caseGRB.BatchStatus.COMPLETED:// print JSON solution into stringSystem.out.println("JSON solution:"+batch.getJSONSolution());// save solution into a filebatch.writeJSONSolution("batch-sol.json.gz");break;default:System.out.println("This should not happen, probably points to a user-memory corruption problem");System.exit(1);break;}}catch(GRBExceptione){// Display batch-error if anybatcherrorinfo(batch);throwe;}finally{// Dispose resourcesbatch.dispose();env.dispose();}}// Discard batch data from the Cluster Managerprivatestaticvoiddiscardbatch(Stringbatchid)throwsGRBException{// Setup a batch connectionGRBEnvenv=setupbatchconnection();// Create batch objectGRBBatchbatch=newGRBBatch(env,batchid);try{// Request to erase input and output data related to this batchbatch.discard();}catch(GRBExceptione){// Display batch-error if anybatcherrorinfo(batch);throwe;}finally{// Dispose resourcesbatch.dispose();env.dispose();}}// Main public functionpublicstaticvoidmain(String[]args){// Ensure enough parametersif(args.length<1){System.out.println("Usage: java Batch filename");System.exit(1);}try{// Create a new batch requestStringbatchid=newbatchrequest(args[0]);// Wait for final statuswaitforfinalstatus(batchid);// Query final status, and if completed, print JSON solutionfinalreport(batchid);// once the user is done, discard all remote informationdiscardbatch(batchid);// Signal successSystem.out.println("OK");}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}catch(Exceptione){System.out.println("Error");}}}
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example reads a MIP model from a file, solves it in batch mode,# and prints the JSON solution string.## You will need a Compute Server license for this example to work.importsysimporttimeimportjsonimportgurobipyasgpfromgurobipyimportGRB# Set up the environment for batch mode optimization.## The function creates an empty environment, sets all necessary parameters,# and returns the ready-to-be-started Env object to caller. It is the# caller's responsibility to dispose of this environment when it's no# longer needed.defsetupbatchenv():env=gp.Env(empty=True)env.setParam("LogFile","batchmode.log")env.setParam("CSManager","http://localhost:61080")env.setParam("UserName","gurobi")env.setParam("ServerPassword","pass")env.setParam("CSBatchMode",1)# No network communication happened up to this point. This will happen# once the caller invokes the start() method of the returned Env object.returnenv# Print batch job error information, if anydefprintbatcherrorinfo(batch):ifbatchisNoneorbatch.BatchErrorCode==0:returnprint(f"Batch ID{batch.BatchID}: Error code{batch.BatchErrorCode} ({batch.BatchErrorMessage})")# Create a batch request for given problem filedefnewbatchrequest(filename):# Start environment, create Model object from file## By using the context handlers for env and model, it is ensured that# model.dispose() and env.dispose() are called automaticallywithsetupbatchenv().start()asenv,gp.read(filename,env=env)asmodel:# Set some parametersmodel.Params.MIPGap=0.01model.Params.JSONSolDetail=1# Define tags for some variables in order to access their values laterforcount,vinenumerate(model.getVars()):v.VTag=f"Variable{count}"ifcount>=10:break# Submit batch requestbatchID=model.optimizeBatch()returnbatchID# Wait for the final status of the batch.# Initially the status of a batch is "submitted"; the status will change# once the batch has been processed (by a compute server).defwaitforfinalstatus(batchID):# Wait no longer than one hourmaxwaittime=3600# Setup and start environment, create local Batch handle objectwithsetupbatchenv().start()asenv,gp.Batch(batchID,env)asbatch:starttime=time.time()whilebatch.BatchStatus==GRB.BATCH_SUBMITTED:# Abort this batch if it is taking too longcurtime=time.time()ifcurtime-starttime>maxwaittime:batch.abort()break# Wait for two secondstime.sleep(2)# Update the resident attribute cache of the Batch object with the# latest values from the cluster manager.batch.update()# If the batch failed, we retry itifbatch.BatchStatus==GRB.BATCH_FAILED:batch.retry()# Print information about error status of the job that processed the batchprintbatcherrorinfo(batch)defprintfinalreport(batchID):# Setup and start environment, create local Batch handle objectwithsetupbatchenv().start()asenv,gp.Batch(batchID,env)asbatch:ifbatch.BatchStatus==GRB.BATCH_CREATED:print("Batch status is 'CREATED'")elifbatch.BatchStatus==GRB.BATCH_SUBMITTED:print("Batch is 'SUBMITTED")elifbatch.BatchStatus==GRB.BATCH_ABORTED:print("Batch is 'ABORTED'")elifbatch.BatchStatus==GRB.BATCH_FAILED:print("Batch is 'FAILED'")elifbatch.BatchStatus==GRB.BATCH_COMPLETED:print("Batch is 'COMPLETED'")print("JSON solution:")# Get JSON solution as string, create dict from itsol=json.loads(batch.getJSONSolution())# Pretty printing the general solution informationprint(json.dumps(sol["SolutionInfo"],indent=4))# Write the full JSON solution string to a filebatch.writeJSONSolution("batch-sol.json.gz")else:# Should not happenprint("Batch has unknown BatchStatus")printbatcherrorinfo(batch)# Instruct the cluster manager to discard all data relating to this BatchIDdefbatchdiscard(batchID):# Setup and start environment, create local Batch handle objectwithsetupbatchenv().start()asenv,gp.Batch(batchID,env)asbatch:# Remove batch request from managerbatch.discard()# Solve a given model using batch optimizationif__name__=="__main__":# Ensure we have an input fileiflen(sys.argv)<2:print(f"Usage:{sys.argv[0]} filename")sys.exit(0)# Submit new batch requestbatchID=newbatchrequest(sys.argv[1])# Wait for final statuswaitforfinalstatus(batchID)# Report final status infoprintfinalreport(batchID)# Remove batch request from managerbatchdiscard(batchID)print("Batch optimization OK")
' Copyright 2025, Gurobi Optimization, LLC'' This example reads a MIP model from a file, solves it in batch mode,' and prints the JSON solution string.'' You will need a Compute Server license for this example to work. */ImportsSystemImportsGurobiClassbatchmode_vb' Set-up the environment for batch mode optimization.'' The function creates an empty environment, sets all neccessary' parameters, and returns the ready-to-be-started Env object to caller.' It is the caller's responsibility to dispose of this environment when' it's no longer needed.PrivateSharedFunctionsetupbatchenv()AsGRBEnvDimenvAsGRBEnv=NewGRBEnv(True)env.CSBatchMode=1env.CSManager="http://localhost:61080"env.LogFile="batchmode.log"env.ServerPassword="pass"env.UserName="gurobi"' No network communication happened up to this point. This will happen' once the caller invokes the start() method of the returned Env' Object.ReturnenvEndFunction' Print batch job error information, if anyPrivateSharedSubprintbatcherrorinfo(ByRefbatchAsGRBBatch)Ifbatch.BatchErrorCode=0ThenReturnConsole.WriteLine("Batch ID: "&batch.BatchID&", Error code: "&batch.BatchErrorCode&"("&batch.BatchErrorMessage&")")EndSub' Create a batch request for given problem filePrivateSharedFunctionnewbatchrequest(ByValfilenameAsString)AsStringDimbatchIDAsString=""' Start environment, create Model object from fileDimenvAsGRBEnv=setupbatchenv()env.Start()DimmodelAsGRBModel=NewGRBModel(env,filename)Try' Set some parametersmodel.[Set](GRB.DoubleParam.MIPGap,0.01)model.[Set](GRB.IntParam.JSONSolDetail,1)' Define tags for some variables in order to access their values laterDimcountAsInteger=0ForEachvAsGRBVarInmodel.GetVars()v.VTag="Variable"&countcount+=1Ifcount>=10ThenExitForNext' submit batch requestbatchID=model.OptimizeBatch()Finallymodel.Dispose()env.Dispose()EndTryReturnbatchIDEndFunction' Wait for the final status of the batch.' Initially the status of a batch is "submitted"; the status will change' once the batch has been processed (by a compute server).PrivateSharedSubwaitforfinalstatus(ByValbatchIDAsString)' Wait no longer than one hourDimmaxwaittimeAsDouble=3600DimstartAsDateTime=DateTime.Now' Setup and start environment, create local Batch handle objectDimenvAsGRBEnv=setupbatchenv()env.Start()DimbatchAsGRBBatch=NewGRBBatch(env,batchID)TryWhilebatch.BatchStatus=GRB.BatchStatus.SUBMITTED' Abort this batch if it is taking too longDimintervalAsTimeSpan=DateTime.Now-startIfinterval.TotalSeconds>maxwaittimeThenbatch.Abort()ExitWhileEndIf' Wait for two secondsSystem.Threading.Thread.Sleep(2000)' Update the resident attribute cache of the Batch object with the' latest values from the cluster manager.batch.Update()' If the batch failed, we retry itIfbatch.BatchStatus=GRB.BatchStatus.FAILEDThenbatch.Retry()System.Threading.Thread.Sleep(2000)batch.Update()EndIfEndWhileFinally' Print information about error status of the job that' processed the batchprintbatcherrorinfo(batch)batch.Dispose()env.Dispose()EndTryEndSubPrivateSharedSubprintfinalreport(ByValbatchIDAsString)' Setup and start environment, create local Batch handle objectDimenvAsGRBEnv=setupbatchenv()env.Start()DimbatchAsGRBBatch=NewGRBBatch(env,batchID)SelectCasebatch.BatchStatusCaseGRB.BatchStatus.CREATEDConsole.WriteLine("Batch status is 'CREATED'"&vbLf)CaseGRB.BatchStatus.SUBMITTEDConsole.WriteLine("Batch is 'SUBMITTED"&vbLf)CaseGRB.BatchStatus.ABORTEDConsole.WriteLine("Batch is 'ABORTED'"&vbLf)CaseGRB.BatchStatus.FAILEDConsole.WriteLine("Batch is 'FAILED'"&vbLf)CaseGRB.BatchStatus.COMPLETEDConsole.WriteLine("Batch is 'COMPLETED'"&vbLf)' Pretty printing the general solution informationConsole.WriteLine("JSON solution:"&batch.GetJSONSolution())' Write the full JSON solution string to a filebatch.WriteJSONSolution("batch-sol.json.gz")CaseElse' Should not happenConsole.WriteLine("Unknown BatchStatus"&batch.BatchStatus)Environment.[Exit](1)EndSelectbatch.Dispose()env.Dispose()EndSub' Instruct cluster manager to discard all data relating to this BatchIDPrivateSharedSubbatchdiscard(ByValbatchIDAsString)' Setup and start environment, create local Batch handle objectDimenvAsGRBEnv=setupbatchenv()env.Start()DimbatchAsGRBBatch=NewGRBBatch(env,batchID)' Remove batch request from managerbatch.Discard()batch.Dispose()env.Dispose()EndSub' Solve a given model using batch optimizationSharedSubMain(ByValargsAsString())' Ensure we have an input fileIfargs.Length<1ThenConsole.Out.WriteLine("Usage: batchmode_vb filename")ReturnEndIfTry' Submit new batch requestDimbatchIDAsString=newbatchrequest(args(0))' Wait for final statuswaitforfinalstatus(batchID)' Report final status infoprintfinalreport(batchID)' Remove batch request from managerbatchdiscard(batchID)Console.WriteLine("Batch optimization OK")CatcheAsGRBExceptionConsole.WriteLine("Error code: "&e.ErrorCode&". "&e.Message)EndTryEndSubEndClass
Help and Feedback