开发者

OpenCms - periodically change content of a file

I'm customizing my OpenCms installation and have cre开发者_运维知识库ated an object that delivers part of my content. The object changes this content once in an hour. Could you please advise me as to how to load this bean at OpenCms startup so that it resides in memory and is able to set up its timer?


After some hours of research and testing I've discovered two ways of doing it:

1) define the class as the Action class of the module - I haven't tested this approach

2) use job scheduler available in the administration layer - this is what I tried and it works fine. You need to create a class that implements I_CmsScheduledJob interface, eg:

package com.xxx.Trial;

import org.opencms.file.*;
import org.opencms.main.*;
import org.opencms.scheduler.I_CmsScheduledJob;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class BuildTagCloud implements I_CmsScheduledJob {
  private String text;

  public String launch(CmsObject object, java.util.Map parameters) throws java.lang.Exception {
   Calendar cal = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   String data = "Last run: " + sdf.format(cal.getTime());
   this.text = data;

   String resname = "/system/modules/com.xxx.Trial/elements/file.jsp";
   // CmsObject object = OpenCms.initCmsObject("Guest");
   object.loginUser("Admin", "admin's password");

   CmsRequestContext cmsContext = object.getRequestContext();
   CmsProject curProject = cmsContext.currentProject();

   if(curProject.isOnlineProject()){
         CmsProject offlineProject = object.readProject("Offline");
         cmsContext.setCurrentProject(offlineProject);
   }
   CmsResource res = object.readResource(resname);
   object.lockResource(resname);
   CmsFile file = object.readFile(res);
   file.setContents(text.getBytes());
   object.writeFile(file);
   OpenCms.getPublishManager().publishResource(object, resname);
   object.unlockResource(resname);

   return text;

  }

}

I hope this can help someone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜