Exemplo - agendar um relatório

Programe um relatório para ser executado em um horário específico ou em horários recorrentes. Por exemplo, talvez você precise executar um relatório diariamente ou fora do horário de pico.

Para agendar um relatório usando o Software Development Kit, crie um objeto schedule e defina os valores apropriados para suas propriedades. Em seguida, use o método add(parentPath, objects, options) para adicioná-lo ao armazenamento de conteúdo.

Esses exemplos de código mostram como agendar um relatório. Por exemplo, alguns grupos em sua organização podem precisar dos dados em um relatório atualizado a cada minuto. Para atender a essa necessidade, você configura uma visualização de relatório, programa o relatório para ser executado a cada minuto e, em seguida, verifica se ele está programado corretamente.

Métodos

Você pode usar o método add(parentPath, objects, options) para agendar um relatório.

Consulte o capítulo Métodos no Guia do Desenvolvedor do Kit de Desenvolvimento de Software para obter as permissões e os recursos necessários para esse método.

Código Java

Para ver o código no contexto, veja o exemplo a seguir:

installation_location/sdk/vb/Scheduler/NewScheduler.java

Os seguintes trechos de código Java™ demonstram como você pode agendar um relatório.

Etapas de um programa Java

  1. Certifique-se de que a conta conectada no momento tenha uma credencial e obtenha uma referência a essa credencial.
    if (! Credentials.hasCredential(connection))
    {
    	Credentials newCred = new Credentials();
    	newCred.addCredential(connection);
    }
    Account logonInfo = Logon.getLogonAccount(connection);
    Credential credential = new Credential();
    StringProp credentialPath = new StringProp();
    String credentialPathString = logonInfo.getSearchPath().getValue();
    credentialPathString = credentialPathString + "/credential[@name='Credential']";
    credentialPath.setValue(credentialPathString);
    credential.setSearchPath(credentialPath);
    BaseClassArrayProp credentials = new BaseClassArrayProp();
    credentials.setValue(new BaseClass[] {credential} );
  2. Defina a data e a hora de início da programação.
    
    public DateTimeProp setScheduleStartDate(Calendar startOnDate)
    {
    	DateTimeProp startDate = new DateTimeProp();
    	//If start date not passed set to today/now
    	if (startOnDate != null)
    		startDate.setValue(startOnDate);
    	else
    		startDate.setValue(Calendar.getInstance());
    
    	return startDate;
    }
  3. Defina a data e a hora de término da programação.
    
    public DateTimeProp setScheduleEndDate(
    	Calendar endOnDate,
    	String endOnTime)
    {
    	DateTimeProp endDate = new DateTimeProp();
    	if (endOnTime.compareToIgnoreCase("onDate") == 0)
    		if (endOnDate != null)
    		{
    			endDate.setValue(endOnDate);
    		}
    		else
    			System.out.println(
    				"Parameter endOnTime cannot be onDate if no enddate provided");
    	return endDate;
    }
    
    public NmtokenProp setScheduleEndTime(String endOnTime)
    {
    	NmtokenProp endTime = new NmtokenProp();
    	if (endOnTime != null)
    	{
    		endTime.setValue(endOnTime);
    	}
    	else
    		System.out.println(
    			"Parameter endOnTime cannot be null! Options: indefinite or onDate");
    	return endTime;
    }
  4. Atribuir o usuário atual como proprietário.
    
    BaseClass[] owners = new BaseClass[] { Logon.getLogonAccount(connection) };
    BaseClassArrayProp ownersProp = new BaseClassArrayProp();
    ownersProp.setValue(owners);
  5. Defina as opções.
    
    OptionArrayProp roap = new OptionArrayProp();
    String reportPath = report.getBaseClassObject().getSearchPath().getValue();
    
    //Set options
    roap.setValue(
    	this.setSchedulerOptions(
    		outFormat,
    		delivery,
    		reportPath,
    		printerName,
    		saveasName,
    		pageOrientation,
    		paper,
    		emails,
    		connection));
    ...
    RunOptionSaveAs saveAs = new RunOptionSaveAs();
    MultilingualToken[] obj = new MultilingualToken[1];
    
    //Set the name of the reportView
    obj[0] = new MultilingualToken();
    obj[0].setLocale("en-us");
    
    //If no name provided use default
    if (saveasName != null)
    {
    	obj[0].setValue(saveasName);
    }
    else
    {
    	obj[0].setValue("View of Report " + reportPath);
    }
    
    //Save the object as report view with name saveasName
    saveAs.setName(RunOptionEnum.saveAs);
    saveAs.setObjectClass(ReportSaveAsEnum.reportView);
    saveAs.setObjectName(obj);
    saveAs.setParentSearchPath(csh.getParentPath(connection, reportPath));
  6. Defina as propriedades do objeto schedule e adicione-o ao relatório.
    newSchedule.setActive(isActive);
    newSchedule.setCredential(credentials);
    newSchedule.setEndDate(this.setScheduleEndDate(endOnDate, endOnTime));
    newSchedule.setEndType(this.setScheduleEndTime(endOnTime));
    newSchedule.setOwner(ownersProp);
    newSchedule.setParameters(pv);
    newSchedule.setOptions(roap);
    newSchedule.setStartDate(this.setScheduleStartDate(startOnDate));
    newSchedule.setType(howOften);
    
    //  add the schedule to the report
    AddOptions ao = new AddOptions();
    ao.setUpdateAction(UpdateActionEnum.replace);
    BaseClass newBc = connection.getCMService().add(
    	new SearchPathSingleObject(reportPath),
    	new BaseClass[] { newSchedule },
    	ao)[0];

Código C#

Para ver o código no contexto, veja o exemplo a seguir:

local_de_instalação/sdk/csharp/Schedule/Schedule.cs

Antes de usar esse exemplo, é necessário criar um objeto de credencial para a conta que você usará para executar o exemplo. Para obter mais informações sobre a criação de credenciais, consulte o Guia de Administração e Segurança.

Os seguintes trechos de código C# demonstram como você pode agendar um relatório.

Etapas de um programa C#

  1. Certifique-se de que a conta conectada no momento tenha uma credencial e obtenha uma referência a essa credencial.
    
    //get the credential for the schedule
    credential schedCred = connection.getCredential();
    baseClassArrayProp credentials = new baseClassArrayProp();
    credentials.value = new baseClass[] {schedCred};
    newSched.credential = credentials;
  2. Defina as datas e horários de início e término da programação.
    // set schedule time to now + 2 minutes
    System.DateTime startTime = new DateTime();
    startTime = DateTime.Now;
    startTime = startTime.AddMinutes(2);
    dateTimeProp schedStartTime = new dateTimeProp();
    schedStartTime.value = startTime;
    newSched.startDate = schedStartTime;
    
    // set schedule end time to now + 5 minutes
    System.DateTime endTime = new DateTime();
    endTime = DateTime.Now;
    endTime = endTime.AddMinutes(5);
    dateTimeProp schedEndTime = new dateTimeProp();
    schedEndTime.value = endTime;
    newSched.endDate = schedEndTime;
    
    // set the schedule end type
    nmtokenProp endType = new nmtokenProp();
    endType.value = "onDate";
    newSched.endType = endType;
  3. Atribuir o usuário atual como proprietário.
    //set the owner
    baseClassArrayProp ownersProp = new baseClassArrayProp();
    baseClass[] owners = new baseClass[]
    	{ SamplesConnect.getLogonAccount(connection) };
    ownersProp.value = owners;
    newSched.owner = ownersProp;
  4. Defina as opções.
    //Set the name of the reportView
    multilingualToken[] reportViewName = new multilingualToken[1];
    reportViewName[0] = new multilingualToken();
    reportViewName[0].locale = "en-us";
    reportViewName[0].value = "View of Report " +
    	reportToSchedule.baseclassobject.defaultName.value;
    
    //Save the output as report view with name saveasName
    runOptionSaveAs saveAs = new runOptionSaveAs();
    saveAs.name = runOptionEnum.saveAs;
    saveAs.objectClass = reportSaveAsEnum.reportView;
    saveAs.objectName = reportViewName;
    saveAs.parentSearchPath = reportToSchedule.parentPath.value;
    
    //Turn off prompting
    runOptionBoolean prompt = new runOptionBoolean();
    prompt.name = runOptionEnum.prompt;
    prompt.value = false;
    
    //set the output format
    runOptionStringArray format = new runOptionStringArray();
    format.name = runOptionEnum.outputFormat;
    format.value = new string[] { "HTML" };
    
    //put the run options where they need to go
    runOption[] schedRunOptArr = new runOption[3];
    schedRunOptArr[0] = saveAs;
    schedRunOptArr[1] = prompt;
    schedRunOptArr[2] = format;
    
    runOptionArrayProp schedRunOptions = new runOptionArrayProp();
    schedRunOptions.value = schedRunOptArr;
    newSched.runOptions = schedRunOptions;
  5. Defina as propriedades do objeto schedule e adicione-o ao relatório.
    //mark the schedule as active
    booleanProp isActive = new booleanProp();
    isActive.value = true;
    newSched.active = isActive;
    
    //Set the type of schedule
    cognosdotnet_10_2.nmtokenProp scheduleType = new nmtokenProp();
    scheduleType.value = "daily";
    newSched.type = scheduleType;
    		
    //make the schedule for every x minutes
    nmtokenProp period = new nmtokenProp();
    period.value = "minute";
    newSched.dailyPeriod = period;
    
    //set that every x minutes to be every 1 minute
    positiveIntegerProp runFreqProp = new positiveIntegerProp();
    runFreqProp.value = "1";
    newSched.everyNPeriods = runFreqProp;
    ...
    searchPathSingleObject reportSearchPath = new searchPathSingleObject();
    reportSearchPath.Value =
    	((baseClass) reportToSchedule.baseclassobject).searchPath.value;
    //  add the schedule to the report
    addOptions ao = new addOptions();
    ao.updateAction = updateActionEnum.replace;
    baseClass newBc = connection.CBICMS.add(
    	reportSearchPath,
    	new baseClass[] { newSched },
    	ao)[0];

Explicação

Para criar a agenda, primeiro você cria um objeto schedule e especifica valores para suas propriedades. A seguir, exemplos de propriedades que podem ser especificadas:

  • active
  • credential
  • dailyPeriod
  • endDate
  • endType
  • everyNPeriods
  • options
  • startDate

Consulte a descrição da classe schedule no capítulo sobre classes do Guia do Desenvolvedor do Kit de Desenvolvimento de Software para obter uma lista completa e uma descrição das propriedades.

Se o relatório contiver prompts, você também deverá especificar parâmetros na propriedade parameters .

A programação em uma matriz schedule é passada para o método add(parentPath, objects, options) e a programação é criada no armazenamento de conteúdo.

Etapas para escrever seus próprios programas

  1. Crie uma matriz de objetos schedule .
  2. Crie um novo objeto schedule .
  3. Crie um novo objeto addOptions .
  4. Crie um objeto dateTimeProp para a data e a hora de início do objeto schedule e defina seu valor como a data e a hora de início necessárias. Atribua esse objeto dateTimeProp à propriedade startDate do cronograma.
  5. Crie uma matriz de objetos option para o objeto schedule . Essas opções serão aplicadas sempre que o relatório agendado for executado. Atribua essa matriz à propriedade value da propriedade options do objeto schedule .
  6. Defina os valores das outras propriedades do objeto schedule .
  7. Adicione o objeto schedule à matriz schedule .
  8. Defina os valores desejados para as propriedades do objeto addOptions .
  9. Chame o método add(parentPath, objects, options) , passando o caminho de pesquisa, a matriz schedule e o objeto addOptions como parâmetros.